+ 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
4 Respostas
+ 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.
+ 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();
+ 1
Thanks Sachintha Sampath
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