[英]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.