这个关键字在java中的接口的默认方法中引用了什么?

时间:2017-03-09 06:10:19

标签: 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

3 个答案:

答案 0 :(得分:0)

我想知道你如何运行这个语法错误的代码?

但是要回答你的问题,$(selector).removeAttr('disabled')只是对象的引用,而对象的实际类不会因为你从超类返回this而改变。如果对象为this(而不是从B派生的内容),则B始终为this.getClass()

PS:请不要将字符串与B.class进行比较。

答案 1 :(得分:0)

这个表示"实现此接口的类的Intance。"在这种情况下。

答案 2 :(得分:0)

默认的接口方法可以使用 this 关键字引用实现该接口的类的实例:

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