简体   繁体   English

在Java接口的默认方法中,此关键字指的是什么?

[英]what does the keyword this refer to in a default method of an interface in java?

I tested the following programms and the result is weird to me where I think it should be A. 我测试了以下程序,结果对我来说很奇怪,我认为应该是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

I wonder how you run this syntactically wrong code? 我想知道您如何运行此语法错误的代码?

But to answer your question, this is just a reference to an object, and the actual class of an object does not change just because you return this from a super class. 但是,为了回答你的问题, this仅仅是一个对象的引用,而实际的类的对象,因为你回不只是改变this从一个超类。 If the object is B (and not something derived from B), then this.getClass() will always be B.class . 如果对象是B (而不是从B派生的对象),则B.class this.getClass()将始终是B.class

PS: Please don't compare strings with == . PS:请不要将字符串与==进行比较。

This means "Intance of the class that implements this interface." 意味着“实现此接口的类的实例”。 in this case. 在这种情况下。

Default methods of interface can refer to the instance of a class that implements the interface using this keyword: 接口的默认方法可以使用以下关键字引用实现接口的类的实例:

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 {}

the code prints: 代码显示:

Current Class Name  = test.C1
Current Class Name  = test.C2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM