gpt4 book ai didi

java - Java继承实例变量

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:40:32 27 4
gpt4 key购买 nike

我知道如果你继承一个类(父类(super class)),它有一个实例变量,它将在子类中被继承。

即:

class Weather {
int humidity;
}

public class Rainy extends Weather {
void changeHumidity() {
humidity = 10;
System.out.println(super.humidity);
}

public static void main(String[] args) {
new Rainy().changeHumidity();
}
}

底线:我想知道为什么实例变量“湿度”在子类和类之间共享。

我知道如果我隐藏它,它就不会被共享,但仍然为什么另一个实例(即使是父类(super class))应该与继承逻辑中的子类共享一个变量。

提前致谢。

最佳答案

Java 的创建者做出了两个决定来指导他们如何设计 Java。一是性能优先,不能因为太慢就判断为不可用。另一个决定是他们将以 C 和 C++ 开发人员为目标,并使 Java 与他们过去使用的类似,以便更容易采用。

因此 Java 像 C++ 一样获得了公共(public)、私有(private)和 protected 访问权限。 package-private 从何而来以及为什么它是默认值尚不清楚。他们可能假设开发人员希望直接访问变量以节省方法调用开销。很久以前我和来自 Marimba 的专业服务人员一起做一个项目,我们有机会调查一些实现代码,这些代码是用很多 package-private 成员编写的。当我问为什么解释是为了表现。这是在像 JIT 这样的优化之前,所以可能有人担心使用访问器方法获取经常使用的父类(super class)成员可能太慢了。另一方面,这可能是一种风格偏好,或者他们正在使用更自由的方法作为不断发展的设计的一部分,也许将 package-private 设置为默认值的想法是应该期望这种自由。 (根据我读过的任何其他代码判断,这不是什么东西。)它是由 Jonathon Payne 和 Arthur Van Hoff 编写的代码,因此专业服务人员可能没有了解真正的原因。

an interview where James Gosling talks about his reasons :

... one of the things that I had wanted to do early on was formalize setting and getting something in the language. You know how in JavaBeans there's this sort of convention that you write setter and getter methods? But I did a bunch of surveys of developers at the time, about whether or not they would like this to be there. And the average person went, "Oh my God!"

And so I didn't do it. But I think in retrospect, I should never have listened to them. I should have just done it. Because, I mean Beans basically layered on this facility that I had wanted to do anyway, but Beans did it as kind of an afterthought.

And because it's layered on as a naming convention, there's some things that don't fit together real well. And so, for instance, it would've made a lot of sense for the default protection for an instance variable to be private. And then the getters and setters, which the system would've known about at a much deeper level, to make them either public or package.

风格演变的方向是更喜欢将实例变量设为私有(private),并在需要时通过 getter 公开它们。您可以指定私有(private)访问修饰符,如下所示:

private int humidity;

然后该变量将对子类不可见。

关于java - Java继承实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14695864/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com