gpt4 book ai didi

java - 为什么这两个代码示例会产生不同的输出?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:07:53 25 4
gpt4 key购买 nike

示例 1:

 class Animal {
public static void saySomething() { System.out.print(" Gurrr!");
}
}
class Cow extends Animal {
public static void saySomething() {
System.out.print(" Moo!");
}
public static void main(String [] args) {
Animal [] animals = {new Animal(), new Cow()};
for( Animal a : animals) {
a.saySomething();
}
new Cow().saySomething();
}
}

输出是:

 Gurrr! Gurrr! Moo!

示例 2:

 class Animal {
public void saySomething() { System.out.print(" Gurrr!");
}
}
class Cow extends Animal {
public void saySomething() {
System.out.print(" Moo!");
}
public static void main(String [] args) {
Animal [] animals = {new Animal(), new Cow()};
for( Animal a : animals) {
a.saySomething();
}
new Cow().saySomething();
}
}

输出:

 Gurrr! Moo! Moo!

我只是不明白为什么将 saySomething 设为非静态会导致对 saySomething 的第二次调用调用 Cow 版本而不是 Animal 版本。我的理解是 Gurrr!哞! Moo! 将是两种情况下的输出。

最佳答案

当您对动物调用 saySomething() 时,动物的实际类型不算数,因为 saySomething() 是静态的。

Animal cow = new Cow();
cow.saySomething();

相同
Animal.saySomething();

一个 JLS 例子:

When a target reference is computed and then discarded because the invocation mode is static, the reference is not examined to see whether it is null:

class Test {
static void mountain() {
System.out.println("Monadnock");
}
static Test favorite(){
System.out.print("Mount ");
return null;
}
public static void main(String[] args) {
favorite().mountain();
}

}

which prints:
Mount Monadnock
Here favorite returns null, yet no NullPointerException is thrown.


资源:

关于同一主题:

关于java - 为什么这两个代码示例会产生不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3680038/

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