[英]what does the keyword this refer to in a default method of an interface in java?
我測試了以下程序,結果對我來說很奇怪,我認為應該是A。
interface O{
default O get(){
return this;
}
}
class A implements O{
public O get(){
return O.super.get();
}
}
class B extends A{
public O get(){
return super.get();
}
}
new B().get().getClass().getName() == B
我想知道您如何運行此語法錯誤的代碼?
但是,為了回答你的問題, this
僅僅是一個對象的引用,而實際的類的對象,因為你回不只是改變this
從一個超類。 如果對象是B
(而不是從B派生的對象),則B.class
this.getClass()
將始終是B.class
。
PS:請不要將字符串與==
進行比較。
這意味着“實現此接口的類的實例”。 在這種情況下。
接口的默認方法可以使用以下關鍵字引用實現接口的類的實例:
package test;
public class ThisInterface {
public static void main(String[] args) {
A1 c1 = new C1();
A1 c2 = new C2();
c1.printCurrentClassName();
c2.printCurrentClassName();
}
}
interface A1 {
default void printCurrentClassName() {
System.out.println("Current Class Name = " + this.getClass().getName());
}
}
class C1 implements A1 {}
class C2 implements A1 {}
代碼顯示:
Current Class Name = test.C1
Current Class Name = test.C2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.