+ 4

Why we can't call child specific methods with the help of parent reference on child object in Java?

class Parent { void m() {} } class Child extends Parent { void n() {} } Parent obj=new Child (); obj.n(); compile time error

17th Jun 2018, 9:55 AM
Nikhil Sharma
Nikhil Sharma - avatar
4 Antworten
+ 1
Imagine that your child class is inheriting the parent class. Then the child class can define it's own methods, that are not defined in the parent class and not inherited by the child class. Java compiler checks compile time polymorphism. There, if you are calling a method of a child object that is defined in the child class itself, by using a parent reference. Compiler checks whether reference type has the method defined in the reference type class? So there is no such method. see.. compiler gives an error.
18th Jun 2018, 1:32 PM
Sachintha Sampath
Sachintha Sampath - avatar
+ 2
on the last line you can't be sure that obj is instance of Child imagine you have method void met(Parent obj){ // you can't know whether obj is Child or Parent } you can use casting ((Child)obj).n();
17th Jun 2018, 10:47 AM
michal
18th Jun 2018, 3:06 PM
Nikhil Sharma
Nikhil Sharma - avatar
0
The reason is: Parent and child method are having different method.(m() and n()) solution: you can do this if parents and child are both having the same method. code: class Parent { void m() { System.out.println("method name : m but i am a parent"); } } class Child extends Parent { void m(){ System.out.println("Method name : m but i am child"); } } public class Main { public static void main (String[]args) { // parent type reference refers to an child object Parent obj=new Child (); obj.m(); } } // output: Method name : m but i am child
18th Jul 2021, 8:35 AM
Arunaa G T
Arunaa G T - avatar