How do I invoke a Parent class method from Child class object in Java?
From what I know, Child class object should invoke it's own implementation of any Parent class method that it has overridden, but what if I need to call the Parent's method implementation using the Child object reference? Does Java even support this?
Sample code for explanation:
public class Main
{
public static void main(String[] args) {
Human obj = new Aman(21);
Aman obj2 = new Aman(21);
System.out.println(obj.getAge()); //prints 20
System.out.println(obj2.getAge()); //also prints 20
System.out.println(obj.super.getAge()); //error here
//how to invoke Human's getAge() method?
}
}
class Human {
int age;
public Human(int age) {
this.age = age;
}
public String getAge() {
return new String("Human's age is "+(this.age));
}
}
class Aman extends Human {
public Aman(int age) {
super(age);
}
public String getAge() {
return new String("Aman's age is "+(this.age-1));
}
}
How do I get my code to print: "Human's age is 21"?