隐藏类的实例变量 [英] Hiding instance variables of a class

查看:111
本文介绍了隐藏类的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么Java对于超类和具有相同名称的实例变量的子类有这种奇怪的行为。

I'm wondering why Java has this strange behavior regarding a superclass and a subclass having instance variables with the same name.

假设我们有以下类定义:

Let's say we have the following class definitions:

class Parent {
    int var = 1;
}

class Child extends Parent {
    int var = 2;
}

通过这样做,我们应该隐藏超类的变量 VAR 。如果我们没有通过 super明确指定访问 Parent var 的方法调用,那么我们永远不能从一个孩子的实例访问 var

By doing this, we are supposed to have hidden the superclass's variable var. And if we do not explicitly specify a way to access Parent's var via a super call, then we should never be able to access var from an instance of a child.

但是当我们有一个演员表时,这个隐藏机制会中断:

But when we have a cast, this hiding mechanism breaks:

Child child = new Child();
Parent parent = (Parent)child;
System.out.println(parent.var); // prints out 1, instead of 2

这不完全绕过整个字段隐藏点?如果是这种情况,那么这不会导致这个想法完全没用吗?

Doesn't this completely circumvent the whole point of field hiding? If this is the case, then doesn't that render the the idea completely useless?

编辑:我指的是本文。它提到


在子类中,超类中的字段不能通过简单引用
名称。相反,字段必须才能通过超级...

Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super...

从我在那里看到的,似乎意味着Java的开发人员在这方面考虑了某种技术。虽然我同意这是一个相当模糊的概念,并且通常可能是不好的做法。

From what I read there, it seems to imply that the developers of Java had some kind of technique in mind in doing this. Though I agree that it is a rather obscure concept and would probably bad practice in general.

推荐答案

在Java中,数据成员不是多态的。这意味着 Parent.var Child.var 是两个不同的变量,碰巧有相同的名字。你在派生类中没有覆盖 var ;正如你自己发现的那样,两个变量都可以相互独立地访问。

In Java, data members are not polymorphic. This means that Parent.var and Child.var are two distinct variables that happen to have the same name. You're not in any sense "overriding" var in the derived class; as you have discovered yourself, both variables can be accessed independently of one another.

最好的前进方式取决于你想要实现的目标:

The best way forward really depends on what you're trying to achieve:


  1. 如果 Parent.var 不应该对 Child ,将其设为私人

  2. 如果 Parent.var Child.var 是两个逻辑上不同的变量,给它们不同的名称以避免混淆。

  3. 如果父.var Child.var 在逻辑上是相同的变量,然后使用一个数据成员。

  1. If Parent.var should not be visible to Child, make it private.
  2. If Parent.var and Child.var are two logically distinct variables, give them different names to avoid confusion.
  3. If Parent.var and Child.var are logically the same variable, then use one data member for them.

这篇关于隐藏类的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆