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?
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.
You just have to create an object of the child class and call the function of the parent class using dot(.) operator.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With