英文:
Why is the compiler not throwing error when Assigning object of sub class to parent reference
问题
class Base {
public void show() {
System.out.println("Base class show() method called");
}
}
class Derived extends Base {
public void show() {
System.out.println("Derived class show() method called");
}
}
public class Main {
public static void main(String[] args) {
Base b = new Derived();
b.show();
}
}
class Derived extends Base {
public void show() {
System.out.println("Derived class show() method called");
}
public void poo() {
System.out.println("take a poo");
}
}
public class Main {
public static void main(String[] args) {
Base b = new Derived();
b.show();
// b.poo(); // This line would result in a compilation error.
}
}
Java allows assigning a reference of a child class to a base class because of polymorphism, but it won't allow accessing methods specific to the child class unless you cast the reference to the child class type.
英文:
class Base {
public void show() {
System.out.println("Base class show() method called");
}
}
class Derived extends Base {
public void show() {
System.out.println("Derived class show () method called");
}
}
public class Main {
public static void main(String[] args) {
Base b = new Derived();//why is java allowing me to create an object of child class
b.show(); //how can the Base class hold and use the reference of child
}
}
What if I create an new method in the child class ??
Will the parent class still be able to access the new method ??
class Derived extends Base {
public void show() {
System.out.println("Derived class show () method called");
}
public void poo() {
System.out.println("take a poo");
}
}
public class Main {
public static void main(String[] args) {
Base b = new Derived();
b.show();
b.poo();
}
}
Why is java allowing me to assign a reference of child to base class and not throwing any warnings or errors.
答案1
得分: 1
这被称为多态性。任何派生类都可以被视为父类的实例(无需显式转换)。
您可以调用的方法和可以访问的字段取决于对象的静态类型。在Base b = new Derived();
的情况下,b
的静态类型是Base
,因此只能调用Base
上可见的方法。在Derived
中定义的新方法无法使用。
英文:
This is called polymorphism. Any derived class can necessarily be considered an instance of a parent class (without explicit casting).
The methods you can call and fields you can access depend on the static type of the object. In the case of Base b = new Derived();
, the static type of b
is Base
, so you can only call methods visible on Base
. New methods defined in Derived
cannot be used.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论