访问子类中的私有超类字段



我知道超类中的私有字段不是由子类继承的,但我的赋值要求我从子类访问私有字段。有一个getter方法,它的问题来自于直接在一个子类方法中引用私有变量:

protected void userPicksUp(Player player) {
System.out.println("What would you like to pick up?");
Scanner keyboard = new Scanner(System.in);
String itemToPickUp = keyboard.nextLine();
if (Utilities.isItemInContainer(itemToPickUp, getRoomObjects())) {
player.addToInventory(itemToPickUp);
roomObjects = Utilities.removeFromList(itemToPickUp, getRoomObjects());
} else {
System.out.println("That item is not in the room");
}
}

对于这个子类方法,我不知道如何从超类访问roomObjects。我无法为此作业创建任何新字段。我还使用了super((作为子类的构造函数,roomObjects也附带了它,所以我真的不明白为什么如果它是我的子类构造函数的一部分,我就不能访问它?

如果我理解正确,您的超类中有一个私有字段无法访问,因为它由于继承甚至关联而不可用。

Utilities.isItemInContainer(itemToPickUp,getRoomObjects(((我认为在这里,要求您访问该私有字段的功能不应该属于这个类或实用程序类。它应该属于你传递itemToPickUp的超类。您可以从实用程序类间接调用它以使其干净。

私有方法就是这样,所以值不会超出类,所以您需要围绕它编写方法,根据需要公开一些功能。这是封装。您的数据被隐藏,这是有原因的私人字段。

最新更新