user2742409 user2742409 - 6 months ago 20
Java Question

Class extends Abstract class implements Interface

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?

Answer

This does work, however it does not make much sense, since the interface is totally obsolete in this case.
You should add the grow method to your AbstractTree like this:

public abstract class AbstractTree{
    protected String barColor;
    protected int maxHeight;
    protected boolean isEvergreen;

    public abstract void grow();
}

Using an interface would make sense, if you wanted to have different kinds of plants that should all be able to grow for instance.

interface Plant{
    void grow();
}

abstract class Tree implements Plant{
    void grow(){ /* do sth */ }
}

abstract class Flower implements Plant{
    void grow(){ /* do sth totally different */
}

The purpose of an interface is to provide the same method in multiple classes with different implementations, whereas an abstract class provides methods and attributes that are shared in all of their child classes.
If a method in an abstract class is also abstract, every child class must implement it themselves.