[英]What is the difference between super and this in terms of inheritence?
这是我的问题,仅在继承的情况下使用super
关键字吗? 在继承方面, this
和super
什么区别?
this
是指当前对象 ,即它是一个引用 super
是指超类 ,即它是一种作用域机制 当前对象与超类的对象相同 。 如果您有一个扩展Animal
的Dog
并执行new Dog()
那么您将创建1个对象,并且该对象既是Animal
实例又是Dog
实例。
这是一个例子
class Dog extends Animal {
public void treatWell(DogSpa spa) {
spa.takeCareOf(this); // pass this object to the spa
}
public void makeSound() {
System.out.println("bark");
super.makeSound(); // call makeSound in Animal scope
}
}
这是指当前对象,而super是指当前对象的父类。
考虑一下:
class Parent {
protected int value;
public void test() {
//print parent
}
}
class Child extends Parent {
public void test() {
//print child
}
private void someMethod() {
this.test();//will print child
super.test();//will print parent
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.