问题
public class Base {
public String Method1() {
System.out.println("Inside Base method 1");
return "";
}
}
class Child extends Base {
static Base o = null;
public String Method1() {
System.out.println("Inside Base method 1");
return "";
}
public String Method2() {
return "Cant be called with base reference";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Base base = new Child();
base.Method1();
base.Method2();***(Error : **The method Method2() is undefined for the type Base**)***
}
}
As the code suggests I want to know, What actually happens in memory allocation that hides Base from calling extra methods of Child and what it is called And is there a way of calling methods via Base. Please help
回答1:
base.Method2() is invalid because Base class has no method with that name, that is the meaning of the error
The method Method2() is undefined for the type Base
since you are doing this:
Base base = new Child();
one option you have is casting, then you can call that method...
Base base = new Child();
base.Method1();
((Child) base).Method2();
回答2:
You need to study more about how polymorphism works. Your instance is a child, but you use it like a Base. Base knows nothing about his children, he only knows his methods. Cast the instance to Child to acces their custom methods.
((Child)base).Method2()
来源:https://stackoverflow.com/questions/45582209/child-method-is-undefined-for-the-type-base