Java中的多态性:为什么我们将父引用设置为子对象? [英] Polymorphism in java: Why do we set parent reference to child object?
问题描述
我想了解为子对象设置父引用的用例. 示例:狗类扩展了动物类. (请注意,没有接口) 我通常会这样创建一个Dog对象:
I want to understand the use-case of setting a parent reference to a child object. Example: Dog class extends Animal class. (No interfaces, mind it) I would normally create an object of Dog like this:
Dog obj = new Dog();
现在,由于Dog是Animal的子类,因此它已经可以访问Animal的所有方法和变量.然后,这有什么不同:
Now, since Dog is a subclass of Animal it already has access to all of Animal's methods and variables. Then, what difference does this make:
Animal obj = new Dog();
请提供一个正确的用例,并附上其使用的代码段.请不要提供有关多态性"或接口编码"的理论文章!
Please provide a proper use-case with an code snippet of it's use. No theoretical articles about 'Polymorphism' or 'Coding to interfaces' please!
代码:
public class Polymorphism {
public static void main(String[] args){
Animal obj1 = new Dog();
Dog obj2 = new Dog();
obj1.shout(); //output is bark..
obj2.shout(); //output is bark..
}
}
class Animal{
public void shout(){
System.out.println("Parent animal's shout");
}
}
class Dog extends Animal{
public void shout(){
System.out.println("bark..");
}
}
class Lion extends Animal{
public void shout(){
System.out.println("roar..");
}
}
class Horse extends Animal{
public void shout(){
System.out.println("neigh");
}
}
在两种情况下输出都是相同的.那么为什么我们将父引用设置为子对象呢?
Output is the same for both the cases. Then why do we set parent reference to child object?
推荐答案
好的.我想我得到了答案.
Okay. I think I got my answer.
public class Polymorphism {
public static void main(String[] args){
Animal obj1 = new Horse();
Horse obj2 = new Horse();
obj1.shout(); //output is neigh..
obj2.shout(); //output is neigh..
obj1.winRaces(); /*But this is not allowed and throws compile time error,
even though the object is of Animal type.*/
}
}
class Animal{
public void shout(){
System.out.println("Parent animal's shout");
}
}
class Horse extends Animal{
public void shout(){
System.out.println("neigh..");
}
public void winRaces(){
System.out.println("won race..");
}
}
因此,当我们将父级引用用于子类对象时,我们无法使用该对象访问子类中的任何特定方法(父类中不存在).
So, when we use parent reference for child class object, we cannot access any specific methods in child class (that are not present in parent class) using that object.
这篇关于Java中的多态性:为什么我们将父引用设置为子对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!