Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling parent class method from child class object in java

Tags:

java

I have a parent class which has a method, in the child class I override that parent class's method. In a third class I make an object of child and by using that object I want call the method of parent class. Is it possible to call that parent class method ? If yes, then how?

like image 340
ranjeet kumar Avatar asked Sep 26 '10 09:09

ranjeet kumar


People also ask

Can I access a parent class method by a child class object?

The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.

How do you call a parent method from child class?

You just have to create an object of the child class and call the function of the parent class using dot(.) operator.

How do you inherit a parent class method to a child class in Java?

Use Java's extends keyword to derive a child class from a parent class, invoke parent class constructors and methods, override methods, and more. Java supports class reuse through inheritance and composition. This two-part tutorial teaches you how to use inheritance in your Java programs.


1 Answers

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.

public class PolyTest{     public static void main(String args[]){         new Child().foo();     }  } class Parent{     public void foo(){         System.out.println("I'm the parent.");     } }  class Child extends Parent{     @Override     public void foo(){         //super.foo();         System.out.println("I'm the child.");     } } 

This would print:

I'm the child.

Uncomment the commented line and it would print:

I'm the parent.

I'm the child.

You should look for the concept of Polymorphism.

like image 178
Erkan Haspulat Avatar answered Sep 17 '22 17:09

Erkan Haspulat