Calling the fruitName method inside Fruit constructor, is actually delegating the call to the child Apple class's method!
public class CallingParentMethodInInheritanceHierarchy {
abstract class Fruit {
String fruitName;
public Fruit(String fruitName) {
this.fruitName = fruitName;
/*
* o/p - Inside constructor - Child: Fruit name is - Apple
*/
System.out.println("Inside constructor - " + fruitName()); // doubt?
}
public String fruitName() {
return "Parent: Fruit name is - " + fruitName;
}
public abstract String type();
}
class Apple extends Fruit {
public Apple() {
super("Apple");
}
public String fruitName() {
/*
* To call the super class method, only way is -
*
* System.out.println(super.fruitName());
*/
return "Child: Fruit name is - " + fruitName;
}
@Override
public String type() {
return "AllSeasonsFruit";
}
}
public static void main(String[] args) {
Fruit fruit = new CallingParentMethodInInheritanceHierarchy().new Apple();
/*
* o/p - Child: Fruit name is - Apple
*/
System.out.println(fruit.fruitName());
}
}
The main attempt behind this, is that I was trying to call the parent method without using the trivial way super.fruitName() call inside a child method.
Please help me @line #12