Is it possible to invoke Parent class method from Child class object in Java?

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"?

>Solution :

The super.getAge() syntax is only available within subclasses. So you could do the following:

class Aman extends Human {
    public Aman(int age) {
        super(age);
    }
    
    public String getAge() {
        return new String("Aman's age is "+(this.age-1));
    }
    
    public String getHumanAge() {
        return super.getAge();
    }
}

The reason for this is that it would break encapsulation if you could just overgo the implementation of the child class by using something like obj.super.getAge() from outside the class of the obj instance.

Leave a Reply