私有字段会被子类继承吗?

发布于 2024-12-15 14:37:27 字数 480 浏览 2 评论 0原文

我读过,子类不能继承私有字段或方法。但是,在此示例中,

class SuperClass {
    private int n=3;
    int getN() {
        return n;
    }
}

class SubClass extends SuperClass {
    public static void main(String[] args) {
        SubClass e = new SubClass();
        System.out.println("n= " + e.getN());
    }
}

当我运行 main 时,我得到的输出为 n=3。这似乎是 SubClass 继承了 SuperClass 的私有属性 n

所以,请解释一下这里发生了什么。谢谢。

I have read that a subclass cannot inherit private fields or methods. However, in this example

class SuperClass {
    private int n=3;
    int getN() {
        return n;
    }
}

class SubClass extends SuperClass {
    public static void main(String[] args) {
        SubClass e = new SubClass();
        System.out.println("n= " + e.getN());
    }
}

When I run main I get the output as n=3. Which seems that SubClass is inheriting the private attribute n from SuperClass.

So, please explain what's going on here. Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

滥情空心 2024-12-22 14:37:28

子类“拥有”其超类的字段,但无法直接访问它们。类似地,子类“具有”私有方法,但您不能直接从子类调用或重写它们。

关于继承的Java文档中,它说

子类继承其父类的私有成员。

但是,我发现将其视为更有用

子类继承父类的私有成员,但无权访问它们

,但这归结为语义。

The subclass 'has' the fields of its superclass, but does not have access to them directly. Similarly, the subclass 'has' the private methods, but you cannot call or override them from the subclass directly.

In the Java documentation on inheritance, it says that

A subclass does not inherit the private members of its parent class.

However, I find it more useful to think of it as

A subclass inherits the private members of its parent class but does not have access to them

but this boils down to sematics.

烟酉 2024-12-22 14:37:28

您正在继承并使用 getn() 方法,该方法是包私有的并且可从子类中使用(因为在本例中两者本质上位于同一个包中。)您无法访问 n 直接,因为它是私有的。 getn() 方法可以访问 n,因为它与 n 位于同一类中,并且您可以访问 getn() 方法,因为它不是私有的。

如果您这样做:

System.out.println("n= "+e.n+"");

...代替当前行,那么由于上述原因,它将无法编译。

通过 setter / getter 方法公开私有变量是完全正常的行为,这本质上就是您在这里所做的。不同之处在于,使用这种方法时,您可以在获取或设置变量时检查/限制/更改/记录/任何变量的值,并且在代码编译时无需进行重大更改即可执行此操作。如果您只是公开字段并让人们直接访问它,则无法执行相同的操作。

You're inheriting and using the getn() method, which is package-private and available from the subclass (since both are inherently in the same package in this case.) You can't access n directly because it's private. It's the getn() method that has access to n because it's in the same class as n, and you have access to the getn() method because it's not private.

If you did:

System.out.println("n= "+e.n+"");

...in place of your current line, then it wouldn't compile for the above reason.

It's perfectly normal behaviour to expose private variables through setter / getter methods, which is essentially what you're doing here. The difference is with this approach you have the potential to check / restrict / alter / log / anything the value of the variable when you get it or set it, and you can do so without making breaking changes when your code compiles. You can't do the same if you just make a field public and let people access it directly.

巴黎盛开的樱花 2024-12-22 14:37:28

这是一个值得讨论的话题。产生混乱的原因是,从技术上讲,子类继承了私有字段,因为私有字段存在于子类中,所以当你调用 getN() 时,它返回 n 的值。所以字段n存在于子类中。如果它不存在,那么当您调用 getN() 时,它会发出错误,因为字段 n 不存在。事实是,它确实存在,并且由于它是在超类中声明的,因此从技术上讲它是由子类继承的。

然而我们(Java程序员以及java官方关于继承的文档)并不考虑这种继承。根据我们的惯例,这不被视为继承,因为您无法直接访问这些字段的值。就好像它们不是您的一样,因为访问它们的唯一方法是使用其他人(不是该超类的子类的类)使用的内容(getter/setter)。

因此,从概念上讲,私有字段不会被继承(尽管它们存在于子类中)。

我认为老师应该比他们更清楚地阐述这一点。仔细一看,确实让人摸不着头脑。

This is a topic worth of discussion. The confusion arises because, technically, the subclass inherits the private fields, because the private fields exist in the subclass, so that when you call getN(), it returns the value of n. So the field n exists in the subclass. If it didn't exist, then when you called getN(), it would issue an error, since the field n doesn't exist. The thing is, it does exist, and since it were declared in the superclass, it technically was inherited by the subclass.

However, we (Java programmers and the java official documentation about inheritance ) don't consider this inheritance. By our convention, this is not considered inheritance, because you cannot access the value of those fields directly. It's almost as if they weren't yours, since the only way to access them is using what everybody else(classes that are not subclasses of that superclass) use (getters/setters).

So, conceptually speaking, private fields are not inherited (although they exist in the subclass).

I think teachers should make this point a lot more clear than they do. After deeply looking at it, it really is confusing.

时间你老了 2024-12-22 14:37:28

子类只能通过 publicprotected 访问方法(getter、setter)访问超类的私有字段。

尝试直接访问私有变量,发现行不通:eg

// won't work
System.out.println("n= "+e.n+"");

The subclass can access the private fields of the super class only via the public or protected access methods (getters, setters).

Try to access the private variable directly and see that it won't work: e.g.

// won't work
System.out.println("n= "+e.n+"");
随风而去 2024-12-22 14:37:28

这将无法编译:

class NewExample extends Example {
    public static void main (String[] args) {
        NewExample e = new NewExample();
        System.out.println("n=" + e.n);
    }
}

因为该变量被声明为private,所以子类无法直接访问它。与方法相同。如果您将 getn() 声明为 private,您也将无法访问它。如果您希望子类能够直接访问n,您可以将其声明为protected int n,这样子类就可以直接修改它。在很多情况下这可能是可取的,也可能不是可取的。

This will fail to compile:

class NewExample extends Example {
    public static void main (String[] args) {
        NewExample e = new NewExample();
        System.out.println("n=" + e.n);
    }
}

Because the variable is declared private, subclasses do not have direct access to it. Same as with methods. If you declared getn() as private, you wouldn't be able to access that either. If you want a subclass to have direct access to n, you can declare it as protected int n and that will allow subclasses to modify it directly. This may or may not be desirable in a lot of circumstances.

束缚m 2024-12-22 14:37:28

这是因为子类的对象正在访问父类中的非私有方法。该方法 getN() 返回父类的私有属性。这就是为什么父类的私有属性的值被继承的原因。我希望这有帮助!

Its because object of child class is accessing method in the parent class which is not private. And that method getN() is returning the private attribute of the parent class. This is why value of private attribute of the parent class is being inherited. I hope this helps!

瑾夏年华 2024-12-22 14:37:28

这是一个很棒的话题,让我和我的教授陷入了争吵。但他耐心地向我解释,证明了他的勇气。

可访问性与继承无关。无论访问修饰符如何,所有属性和方法都由子类继承。

虽然子类无法访问属性或方法,但它仍然继承它们!

每种编程语言对上述继承和可访问性概念都有自己的解释。

This is a great topic which dragged me and my professor into a quarrel. But he proved his mettle by explaining me with patience.

Accessibility has nothing to do with Inheritance. All the attributes and methods are inherited by the child classes irrespective of the access modifiers.

Though the child class can't access the attributes or methods, it still inherits them!

Every programming language has its own interpretation of the above concept of inheritance and accessibility.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文