last weekend i read some stuff about interfaces, abstract classes and design principles. At the end i got a bit confused and i tried to build an example of what i learned (or thought i had learned).
Here is my example: The case would be to model a class that holds informations about trees.
First of all i would make an interface:
public interface Tree{
public void grow();
}
The interface holds all methods that should be implemented by the concrete trees. So far so good but such a tree needs some attributes (variables) that are shared over all tree families. For that purpose i would use a abstract class:
public abstract class AbstractTree implements Tree {
private String barColor;
private int maxHeight;
private boolean isEvergreen;
}
Is this the right way or am i not able to make a kind of contract about attributes (variables) that should be in the other classes?
After the attribute part is done i would like to have 3 type of trees.
- Oak
- Maple
- Spruce
So each of these tree "tpyes" can have individual variables.
public class OakTreeImpl extends AbstractTree{
private String barColor;
private int maxHeight;
private boolean isEvergreen;
private String foo;
@Override
public void grow() {
}
}
Does this approach sound right in an object-oriented design principles way or am i totally wrong with it?
protected
fields so you don't need to redeclare them in the implementation – OneCricketeer May 30 '16 at 9:31public int getMaxHeight(){return this.maxHeight;}
You can still override them later in the implementation, but it's not forced. If you want to force overriding, then declare them in the abstract class aspublic abstract int getMaxHeight();
– Draken May 30 '16 at 9:43