从超类 (JAVA) 访问私有变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19843021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:38:05  来源:igfitidea点击:

Access a private variable from the superclass (JAVA)

javainheritance

提问by NerdsRaisedHand

Ok so I have studied java all semester and thought I had a clear understanding about inheritance and super/sub classes. Today we were given as assignment for making a superclass called enemy, with sub classes of different types of enemies. I did everything fine and all of my subclasses are working, but when I went back to read the guidelines we must follow, I found this sentence:

好的,所以我整个学期都学习了 Java,并认为我对继承和超/子类有了清晰的了解。今天,我们的任务是创建一个名为敌人的超类,其中包含不同类型敌人的子类。我做的一切都很好,我的所有子类都在工作,但是当我回去阅读我们必须遵循的指南时,我发现了这句话:

"All member variables of the super class must be private. Any access to a variable must be done through protected methods in the subclasses."

“超类的所有成员变量都必须是私有的。对变量的任何访问都必须通过子类中的受保护方法完成。”

From what I have learned, this makes no sense to me. If a variable is private within the superclass, doesn't that disallow access even from a subclass? The last part that talks about protected methods in the subclasses also doesn't make any sense to me. How does this help and/or allow any access whatsoever to the super class?

从我所学到的,这对我来说毫无意义。如果一个变量在超类中是私有的,那么即使来自子类也不允许访问吗?讨论子类中受保护方法的最后一部分对我来说也没有任何意义。这如何帮助和/或允许对超类进行任何访问?

From what I've learned about inheritance, Below is what i thought was true:

根据我对继承的了解,以下是我认为正确的:

                Access Levels
 Modifier    Class  Package Subclass    World
 public        Y      Y        Y        Y
 protected     Y      Y        Y        N
 no modifier   Y      Y        N        N
 private       Y      N        N        N

If I'm understanding something wrong here please do explain! I don't want to confront the instructor about giving us faulty instructions, if I'm the one not understanding it correctly!

如果我在这里理解错误,请解释!我不想因为给我们错误的指示而与教练对质,如果我是那个没有正确理解它的人!

采纳答案by Cyrille Ka

The part

那个部分

Any access to an a variable must be done through protected methods in the sub classes.

... just means that the subclasses have to call protected methods that are defined in the superclass. Since these methods are protected they can be accessed by the subclasses.

...只是意味着子类必须调用在超类中定义的受保护方法。由于这些方法是受保护的,它们可以被子类访问。

First you would define a base class like this:

首先,您将定义一个这样的基类:

public class Base {

    private int x;  // field is private

    protected int getX() {  // define getter
        return x;
    }

    protected void setX(int x) {  // define setter
        this.x = x;
    }
}

Then you would use it in your child class like this:

然后你会像这样在你的孩子班级中使用它:

class Child extends Base{

    void foo() {
        int x = getX(); // we can access the method since it is protected.
        setX(42);  // this works too.
    }
}

回答by Iulian Rosca

Probably the sentence is not worded correctly, from what I understand it makes perfect sense to me :
1. the superclass has private fields and protected methods to access them
2. the subclasses access the fields by using that methods.

可能这句话措辞不正确,据我所知,这对我来说很有意义:
1. 超类具有私有字段和访问它们的受保护方法
2. 子类使用该方法访问字段。

回答by sdanzig

Those are just the constraints of the assignment, not Java itself. You could give the superclass protected data members, and then access those directly from the subclass. However, the professor likely wishes to teach you about how a superclass can protect its data members from direct access by a subclass, and protected methods would be a way to do that.

这些只是赋值的约束,而不是 Java 本身。您可以为超类提供受保护的数据成员,然后直接从子类访问这些成员。但是,教授可能希望教您了解超类如何保护其数据成员免受子类的直接访问,而受保护的方法将是一种方法。

回答by Marko Topolnik

You are right in your thinking that, literally speaking, you can't access a superclass's private field. The text of your assignment uses wording which is not 100% strict, but is 100% customary in Java parlance: the so-called "getter" methods, also called "accessor" methods, are seen as "accessing the field", even though, strictly speaking, they merely return the current valueof the field—which is definitely not the same as giving access to the field itself. You just need to get used to this (and many more) conventions in the Java jargon.

您的想法是正确的,从字面上看,您无法访问超类的私有字段。您的赋值文本使用的措辞不是 100% 严格,而是 100% 习惯于 Java 用语:所谓的“getter”方法,也称为“accessor”方法,被视为“访问字段”,即使,严格来说,它们只是返回字段的当前值——这绝对不同于授予对字段本身的访问权限。您只需要习惯 Java 术语中的这个(以及更多)约定。

回答by Pedro Vítor

When you inheritance other class, you cannot access your private attributes directly. So, if you have a class named "A" and other called "B", and make B extends A, B cannot access private attributes of A.

当您继承其他类时,您无法直接访问您的私有属性。因此,如果您有一个名为“A”的类和另一个名为“B”的类,并使 B 扩展 A,则 B 无法访问 A 的私有属性。

Think this like a protection. This way, you can write some attributes in class "A" that you dont want others classes access it through inheritance.

认为这是一种保护。这样,您可以在类“A”中编写一些您不希望其他类通过继承访问它的属性。

The "B" class can access only public, protected and default attributes directly in "A" class. But if you want to access a private attribute in "A" class for any reasons, you can write a method in "A" to return this attribute.

“B”类只能直接访问“A”类中的公共、受保护和默认属性。但是如果你因为任何原因想要访问“A”类中的一个私有属性,你可以在“A”中编写一个方法来返回这个属性。

public class A{
    private int foo;
    public int getFoo(){
       return this.foo;
    }
}

public class B extends A{
    public void doSomething(){
       getFoo(); //return the private foo attribute of superclass
    }
}

回答by sarath

package com.action.product;

public class ProductAction{
  public static String strCategoryName;

  public String getStrCategoryName() {
    return strCategoryName;
  }
  public void setStrCategoryName(String strCategoryName) {
    this.strCategoryName = strCategoryName;
  }

}

-----------------------------------------------------------------------

package com.DAO.product;

public class ProductDAO extends ProductAction {

   @SuppressWarnings("static-access")
   public String addnewProductValidation(){
       System.out.println("======through_name======="+super.strCategoryName);

       System.out.println("======through_getters======="+super.getStrCategoryName());

   }
}

Can initialize variables as static. No need to create object

可以将变量初始化为静态。无需创建对象