简体   繁体   English

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

[英]Accessing private superclass field in subclass

I know that private fields in a superclass are not inherited by the subclass but my assignment requires me to access a private field from a subclass.我知道超类中的私有字段不被子类继承,但我的任务要求我从子类访问私有字段。 There is a getter method for it by problem comes from referencing the private variable directly in one of the subclasses methods:它有一个 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");
    }
}

I can't figure out how to access roomObjects from the superclass for this subclass method.我不知道如何从这个子类方法的超类访问 roomObjects。 I cannot make any new fields for this assignment.我无法为此作业创建任何新字段。 I have also used super() for the subclass' constructor and roomObjects came with that so I don't really understand why I can't access it if it is part of my subclass' constructor?我还为子类的构造函数使用了 super(),并且 roomObjects 随之而来,所以我真的不明白如果它是我的子类构造函数的一部分,为什么我不能访问它?

If I understand correctly, there is a private field in your superclass that you cannot access as it is not available due to inheritance, or even association.如果我理解正确,您的超类中有一个私有字段您无法访问,因为它由于 inheritance 甚至关联不可用。

Utilities.isItemInContainer(itemToPickUp, getRoomObjects() I think here, the functionality that requires you to access that private field should not belong in this class, or utility class. It should belong to your superclass where you pass the itemToPickUp. You can indirectly call it from utility class to make it clean. Utilities.isItemInContainer(itemToPickUp, getRoomObjects()我认为在这里,需要您访问该私有字段的功能不应该属于此 class 或实用程序 class。它应该属于您传递 itemToPickUp 的超类。您可以间接调用它来自实用程序 class 以使其清洁。

A private method is so, so the value does not go outside the class, so you need to write methods around it, exposing bits of functionality as per requirement.私有方法是这样的,因此该值不会在 class 之外的 go ,因此您需要围绕它编写方法,根据要求公开一些功能。 This is encapsulation.这是封装。 Your data is hidden, a private field for a reason.您的数据是隐藏的,一个私有字段是有原因的。

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

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