【问题标题】:why this keyword is used in java interface and what does it refer?为什么在 java 接口中使用这个关键字,它指的是什么?
【发布时间】:2017-08-04 11:21:22
【问题描述】:

我只是想我可以在interface 中使用this 关键字。

那么,如果this 关键字代表class 中的当前class 对象引用,那么它在interface 中代表什么?

interface InterfaceOne {

    default void display() {
        this.defaultMethod();
        System.out.println("InterfaceOne method displayed");
    }

    default void defaultMethod() {
        System.out.println("defaultMethod of InterfaceOne called");
    }

}

【问题讨论】:

  • 当前Object 实例在它当前引用的范围内。
  • 在这个地方使用this 和在普通的class 中一样已经过时了。如果你只写defaultMethod(),而不用过时的this,想想会发生什么可能会有所帮助。然后考虑在添加 this. 时没有任何变化

标签: java interface java-8 this keyword


【解决方案1】:

即使在这种情况下,this 关键字也用于相同的上下文和含义。

您缺少的一件事是,this 关键字代表当前的“Object”,而不是当前的“Class”。因此,如果并且当您创建此 "Interface" 的对象(当然通过在另一个类中实现它),this 关键字将代表该特定对象。

例如,如果你有,

class ClassOne implements InterfaceOne{
}

那么,你可以拥有,

InterfaceOne one = new ClassOne();

one.display(); // Here, the "this" keyword in your display method, will refer to the object pointed by "one".

希望这会有所帮助!

【讨论】:

  • 只是要补充一点,this 的唯一例外是在另一个构造函数中调用重载的构造函数。
  • 是的。但在这个问题中,上下文是使用this 作为自引用指针。这就是为什么我说相同的上下文和含义。
【解决方案2】:

“this”表示实现接口的新Instance

public interface InterfaceTest {
    default void display() {
        this.defaultMethod();
        System.out.println("InterfaceOne method displayed");
    }

    default void defaultMethod() {
        System.out.println("defaultMethod of InterfaceOne called");
    }
}

public class TestImp implements InterfaceTest {

    @Override
    public void defaultMethod() {
        System.out.println("xxxx");
    }
}

public class Test {
    public static void main(String args[]) {
        TestImp imp=new TestImp();
        imp.display();
    }
}

//console print out:
xxxx
InterfaceOne method displayed

【讨论】:

    猜你喜欢
    • 2016-09-25
    • 2013-03-16
    • 2018-02-11
    • 2019-06-22
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多