Java:如何从接口方法访问属性

问题描述 投票:0回答:3

我创建一个界面如下:

// The OnClickListener interface :
public interface OnClickListener{

    void onClick(); 

}

并且我创建一个Person类:

// Class Person :
public class Person
{
    String name;

    OnClickListener onClicklisner;

    Person(String name) 
    {   
        this.name = name;

        this.onClickListener = new OnClickListener() 
        {      
           @Override
            public void onClick() {

                //I want to access to this.name attribute, but it doesn't work :
                System.out.println(this.name);
            }
        };
    }
}

在上面的onClick()方法中,我想访问this.name属性,但是它不起作用。

我如何访问它?

非常感谢。

java methods interface attributes
3个回答
2
投票
//I want to access to this.name attribute, but it doesn't work :
  System.out.println(this.name);

此处this指的是没有OnClickListenername对象>

如下使用name代替this.name

this.onClicklisner = new OnClickListener()
{
    @Override
    public void onClick() {

        //I want to access to this.name attribute, but it doesn't work :
        System.out.println(name);
    }
};

2
投票

您应该在其前面加上类名Person.this.name


0
投票

pbaris使用Person.this.name的方法有效,但是您也可以使用getter并使用getName(),或者,如果您声明字段name为final,则可以直接使用name而没有前缀。


0
投票

您已经陷入Java的通用范围陷阱,并且这种方法违反了接口的目的。在以下代码行上,您实例化了一个匿名类:

© www.soinside.com 2019 - 2024. All rights reserved.