Java中的父类和子类可以具有相同的实例变量吗? [英] Can parent and child class in Java have same instance variable?

查看:266
本文介绍了Java中的父类和子类可以具有相同的实例变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这些类:

class Parent {
 int a;
}

class Child extends Parent {
 int a; // error?
}

声明 a 中由于多次声明 int a 而没有给出编译错误?

Should the declaration of a in Child not give compilation error due to multiple declarations of int a?

推荐答案

child.a 阴影(或隐藏 parent.a

这是合法的Java,但应该避免。我希望您的IDE可以选择向您发出警告。

It's legal Java, but should be avoided. I'd expect your IDE to have an option to give you a warning about this.

但请注意,这只是一个问题,因为您已经暴露了变量走向世界。如果确保所有变量都是私有的(从方法的API中分离出方法的API)那么父和子是否具有相同的字段名称并不重要 - 孩子不会无论如何能够看到父母的字段。如果你将一个方法从孩子移动到父母,这可能会引起混淆,并且它的可读性通常不是很好,但它比隐藏情况更好。

Note, however, that this is only an issue because you're already exposed a variable to the world. If you make sure that all your variables are private to start with (separating out the API of methods from the implementation of fields) then it doesn't matter if both the parent and the child have the same field names - the child wouldn't be able to see the parent's fields anyway. It could cause confusion if you move a method from the child to the parent, and it's not generally great for readability, but it's better than the hiding situation.

这篇关于Java中的父类和子类可以具有相同的实例变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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