[英]If parent and child class are having same methods and i am using the reference of parent class to store the object of child class
Parent class父类
class Animal {
public void sound() {
System.out.println("Grr");
}
}
Child class儿童班
class Dog extends Animal {
public void sound() {
System.out.println("Woof");
}
}
Calling class调用类
class Callings {
public static void main(String args[]) {
Animal a = new Dog();
a.sound();
}
}
Output is - "Woof"输出是 - “Woof”
My concern is--> I have read till now that if we use the parent class reference and point to object to child class then using the reference of parent class we can only access the data members and methods of the parent class only, if this is true then output of above code should be "Grr".我的担忧是-->我已经读到,如果我们使用父类引用并指向子类的对象,那么使用父类的引用我们只能访问父类的数据成员和方法,如果这样为真,则上述代码的输出应为“Grr”。 But the output is "Woof" can any one explain why.
但是输出是“Woof”,任何人都可以解释原因。
Even you are creating and object for Animal
but the instance is type of Dog
, you can create an instance of a child class and assign to the type of parent.即使您正在为
Animal
创建和对象但实例类型为Dog
,您也可以创建子类的实例并分配给父类的类型。
When you call a method, it should be defined in the parent class and if it is overridden in child then the child method will be called else the parent's method will be called.当您调用一个方法时,它应该在父类中定义,如果它在子类中被覆盖,则将调用子方法,否则将调用父类的方法。
You can check the type of the instance by printing the class type of the instance a
by using System.out.println(a.getClass().getName());
您可以通过使用
System.out.println(a.getClass().getName());
打印实例a
的类类型来检查实例的类型System.out.println(a.getClass().getName());
which will print Dog
这将打印
Dog
In java when your child class has a function named the same as the parent class, it overrides it.在java中,当你的子类有一个与父类同名的函数时,它会覆盖它。 In your instance, you have a parent function called "sound".
在您的实例中,您有一个名为“声音”的父函数。
public void sound() {
System.out.println("Grr");
}
When you name the child function "sound" then you override the parent one.当您将子函数命名为“声音”时,您将覆盖父函数。
public void sound() {
System.out.println("Woof");
}
So every time you override a parent function then the child function will be called.因此,每次覆盖父函数时,都会调用子函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.