The way to do that is based on Object Oriented programming
public class NotPancake extends Pancake {
@Override
public boolean shouldEat() {
return true;
}
}
The magic that happens here is called "inheritance," and is one of four elements assigned to OO.
What happens here is that you define new structure that is delivered from Pancake.
This means that NotPancake
inherits form Pancake
. So a NotPancake is a Pancake.
Pancake p = new Pancake();
Pancake q = new NoPancake();
print(p.shouldEat()); //Will be false
print(q.shouldEat()); //Will be true
This relation gives us the possibility to change the behavior, we are allowed to redefine all public, protected and defaults methods from super class.
The when in our child class we define a method with the same signature we say that this method override the previous one. In Java you should add the annotation @Override
to inform compiler additionally about it.
This is one way to do it. The inheritance is simple but create a lot of issue in coding complex programs an alternative solution is called composition. and you should always prefer composition over inheritance.
The composition is based on the abstractness. To use it a interface
is required. The interface is an description of an contract that classes that implements it follow.
public interface Dish {
boolean isEatable();
}
The name of interface should represent some abstract general concept.
public class Pancake implements Dish {
@Override
public boolean shouldEat() {
return false;
}
}
public class Carrot implements Dish {
@Override
public boolean shouldEat() {
return true;
}
}
Usage is more less the same.
Dish dish1 = new Pancake();
Dish dish2 = new NoPancake();
print(dish1.shouldEat()); //Will be false
print(dish2.shouldEat()); //Will be true
On this small example is hard to show the benefits for composition. But is demonstrate the coding to interface approach.