簡體   English   中英

在繼承方面,super和this有什么區別?

[英]What is the difference between super and this in terms of inheritence?

這是我的問題,僅在繼承的情況下使用super關鍵字嗎? 在繼承方面, thissuper什么區別?

  • this是指當前對象 ,即它是一個引用
  • super是指超類 ,即它是一種作用域機制

當前對象與超類的對象相同 如果您有一個擴展AnimalDog並執行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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM