简体   繁体   English

访问已实现类中的实例变量

[英]Accessing instance variables in implemented class

I am completing an assignment and I was provided an interface called Place .我正在完成一项作业,并为我提供了一个名为Place的界面。 It has several defined methods and no variables.它有几个定义的方法,没有变量。 I created a class that implements Place and this contains a string variable name and all the methods from the Place interface.我创建了一个实现Place的类,它包含一个字符串变量名称和来自Place接口的所有方法。

public class PlaceImpl implements Place
{
    public String name;
    ...
}

I then create an object然后我创建一个对象

Place p = new PlaceImpl(placeName);

However, when I try to access p.name I get the error "cannot find symbol".但是,当我尝试访问 p.name 时,出现错误“找不到符号”。 Can I access instance variables in this way or do I just need to find somewhere else to store my variables?我可以通过这种方式访问​​实例变量还是我只需要找到其他地方来存储我的变量? Thanks谢谢

Update: I cannot change the Place interface and I have to use a variable of type Place to integrate with the rest of the code I was provided.更新:我无法更改 Place 界面,我必须使用 Place 类型的变量与我提供的其余代码集成。

Since you can't change the Place interface to add a getName() method, maintain a Map<Place,Name> .由于您无法更改Place接口以添加getName()方法,因此请维护一个Map<Place,Name>

enum PlaceNameMap implements Function<Place,Name>, Supplier<Place> {
    INSTANCE;

    private Map<Place,String> map = new HashMap<>();

    public Place createPlace(String name) {
        PlaceImpl result = new PlaceImpl(name);
        add(result, name);
        return result;
    }
    public void add(Place p, String name) {
        map.put(p, name);
    }
    public String apply(Place p) {
        return map.get(p);
    }
}

You can access name by first casting type PlaceImpl to p .您可以通过首先将类型PlaceImplp来访问name For example, assigning name to String variable myName :例如,将name分配给 String 变量myName

String myName = ((PlaceImpl) p).name;

Sorry for the really late reply but I just came across the same problem and figured it out.很抱歉回复太晚了,但我刚刚遇到了同样的问题并想通了。

You are on the right track - if you change your code to:您走在正确的轨道上 - 如果您将代码更改为:

PlaceImp p = new PlaceImp(placeName);

you will find that your code will work because your static type is now PlaceImp and PlaceImp contains the instance variable you are looking for as a public element.您会发现您的代码将起作用,因为您的静态类型现在是 PlaceImp,而 PlaceImp 包含您正在寻找的实例变量作为公共元素。

On the other hand, if your static type is Place (as in your example code), it does not contain an element called 'name' and thus you cannot access it.另一方面,如果您的静态类型是 Place(如您的示例代码中所示),则它不包含名为 'name' 的元素,因此您无法访问它。

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

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