[英]What is the difference between super and this in terms of inheritence?
Here is my question, super
keyword is used only in case of inheritence ? 这是我的问题,仅在继承的情况下使用super
关键字吗? In terms of inheritence, what is the difference between this
and super
? 在继承方面, this
和super
什么区别?
this
refers to the current object , ie it's a reference this
是指当前对象 ,即它是一个引用 super
refers to the super class , ie it's a scoping mechanism super
是指超类 ,即它是一种作用域机制 The current object is the same object as the object of the superclass. 当前对象与超类的对象相同 。 If you have a Dog
that extends Animal
, and do new Dog()
then you create 1 object, and this object is both the Animal
instance and the Dog
instance. 如果您有一个扩展Animal
的Dog
并执行new Dog()
那么您将创建1个对象,并且该对象既是Animal
实例又是Dog
实例。
Here's an example 这是一个例子
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
}
}
this refers to current object, while super refers to current object's parent class. 这是指当前对象,而super是指当前对象的父类。
Consider this: 考虑一下:
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.