Lecture 16 - Interfaces

Lecture 16 - Interfaces - return color; } } A class may...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Interfaces An interface is a collection of o Unimplemented declaration of methods, and/or o Class constants An interface takes the idea of an abstract class to its logical extreme o Contains no code (i.e. no implementation) o Is an expression of pure design o General form: accessKeyword interface Name { } Eg: public interface Color { static final int RED = 0; static final int BLUE = 1; static final int YELLOW = 2; public void setColor(int color); public int color(); } Implementing Interfaces Any class can implement an interface o Use the implements keyword o Provide code for all methods in the interface o Eg: public class Point extends Object implements Color { private double x, y; private int color = RED; ... public void setColor(int color) { this.color = color; }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
public int color() {
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: return color; } } A class may implement more than one interface o Eg: public class Point extends Object implements Color, Clonable { } Interfaces give Java some of the power of multiple inheritances, without any of its problems o However, there is no code reuse, since each class must re-implement the methods An interface is normally put into its own Java source file o Eg: Color.java Interface Inheritance Interfaces can extend one or more super-interfaces o A sub-interface inherits all the constants and method declarations from its super-interfaces May also add its own o Eg: public interface Measurable extends Weight, Volume, Velocity { // Additional method declarations and/or constants here }...
View Full Document

Page1 / 2

Lecture 16 - Interfaces - return color; } } A class may...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online