I made a java interface called Polygon, it contains various abstract methods like getArea() and getNVertices(). It will be implemented by subclasses such as Triangle, Quadrilateral etc. which in turn are extended (e.g., Quadrilateral is extended by Rectangle).
Now each Polygon will be defined by a number of vertices (I put them in an array of Vertex, which contains the x and y coordinates). As each Polygon will use this array, I'm wondering: is it possible to define an array of Vertex in the interface Polygon? How do I do this?
5 Answers 5
A common practice in this case is to write both an interface and an abstract class.
The interface defines the contract of the polygon, while the abstract class contains the default implementation - which can include attributes like an array of vertices, and any methods you want to have default implementation for.
So you will have something like:
public interface Polygon { ... }
And in another file
public abstract class BasePolygonImpl implements Polygon {
protected Vertex[] vertices;
// ...
}
The reason for this is that if a person wants to create a Polygon which is implemented in a different way (for example, has a linked list of vertices or keeps its vertices in a database), they can create a class that implements Polygon and ignores the BasePolygonImpl class.
But if they want to implement a polygon which extends rather than replaces the default implementation, they can decide to use BasePolygonImpl as their superclass, and so to avoid repeating the base implementation.
The important point to notice is that interfaces do not define implementation, thus cannot include fields other than constants. Only classes can define implementation.
Comments
You cannot define variables (attributes are going to be static and final) inside an interface. Your solution would be implementing it by an abstract class.
Comments
Java interfaces cannot have instance variables. If having them seems really appropriate to you, perhaps you should consider using an abstract class instead (or in addition) to an interface.
Comments
All variable inside an interface are public static final ,
if you put the vertex[] in Polygon interface only one instance of Vertex will be created for all the instance of triangle, Quadrilateral.
you could add vertex[] is all your sub-classes(triangle,etc) then declare getters and setters of Vertex[] in the Polygon interface. or you could use abstract class as other friend mentioned above.
Comments
Alternate suggestion: If every Polygon is required to have a list of Vertex, then you could define an interface method:
List<Vertex> getVertices();
If your Polygons are immutable, which would be a wise idea, then you could recommend Polygon implementors to return a com.google.common.collect.ImmutableList or something like.
abstract classthan aninterface.