2017-02-18 70 views
-2

所以我只是在寻找澄清。我有一个equals方法,它可以通过传入对象的cv.ch返回实例变量而不用返回它的方法。这是怎么回事?了解如何返回实例变量而无法返回它

public static class Test { 
    private int v; 

    private char ch; 

    public Test(int v, char ch) { 

     this.v= v; 

     this.ch= ch; 

    } 

    public boolean equals(Object o) { 
     if (this == o) return true; 
     if (o == null || this.getClass() != o.getClass()) 
      return false; 
     Test cv = (Test) o; 
     if (this.v == cv.v && this.ch == cv.ch) 
      return true; 
     return false; 

    } 

} 

编辑:我改写我的问题,使其更好地理解

+0

*“我以为你总是需要一种方法来返回实例变量?” - - 这是不正确的。 –

回答

0

的私有成员变量都拥有它们,测试类访问。任何在Test中的代码都可以访问这些字段,而不管它是通过“this”还是其他变量。

特别是JLS指出“如果成员或构造函数被声明为私有的,那么当且仅当它存在于包含成员声明的顶级类(§7.6)的主体内时才允许访问或构造函数“。