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

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

问题描述

我想知道为什么 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 调用访问 Parentvar 的方法,那么我们将永远无法访问 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?

编辑:我特指这篇文章 在 Java 教程中.它提到

EDIT: I am referring specifically to this article in the Java Tutorials. It mentions

在子类内,不能引用超类中的字段以其简单的名称.相反,该字段必须通过超级访问...

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.varChild.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 可见,请将其设为 private.
  2. 如果 Parent.varChild.var 是两个逻辑上不同的变量,请为它们指定不同的名称以避免混淆.
  3. 如果 Parent.varChild.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天全站免登陆