I am attempting to get a superclass method to run on subclass methods/fields when called by the subclass. For instance
public class CoffeeMachine() {
protected int cost = 3;
protected int getCost() {
return cost;
}
}
public class FancyCoffeeMachine() extends CoffeeMachine{
protected int cost = 6;
}
main{
FancyCoffeeMachine expensive = new FancyCoffeeMachine();
System.out.println(expensive.getCost());
}
I would like this to print 6, but it prints 3 instead. I want to make this as DRY as possible, so I am trying to avoid making a second getCost() method. Is there any way to do this? How can I get a superclass method to use subclass variables, when called by the subclass? The same thing happens with methods: if I have
public class makeCoffee() {
System.out.println("Coffee cost " + this.getCost());
}
the output will be "Coffee cost 3" even when I call makeCoffee on a FancyCoffeeMachine. Why is this? How can I fix it? Or is there a better way to implement this object structure that completely circumvents this mistake?