Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading