Java中的静态变量 [英] Static variable in Java

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

问题描述

根据Java,静态变量可以通过类名访问,但是它们也可以被类对象访问,即使Java不建议它,它也给出了相同的答案。



我知道变量只有一个副本,其值对于所有对象和其他东西都是相同的。为什么Java建议使用类名而不是类对象?

解决方案

因为它可能令人困惑!静态成员没有动态调度。



看看这个令人困惑的代码:(可能是语法错误;我的Java生锈了)

  public abstract class Singer {
public static void sing(){
System.out.println(Singing);
}
}

公共类Soprano延伸歌手{
public static void sing(){
System.out.println(在范围内唱歌 C4-A5);
}
}

公共类MyDriver {

public static void main(String [] argv){
Singer mySoprano1 = new Soprano ();
女高音mySoprano2 =新女高音();
mySoprano1.sing();
mySoprano2.sing();
}

}

查看 MyDriver 令人困惑,因为似乎 sing 方法是多态的,所以输出应该是......

 在C4-A5 
范围内演唱唱歌在C4-A5


...因为 soprano1 soprano2 都是实例 Soprano - 不是歌手



但是,唉,输出实际上是:

 唱歌
唱歌范围为C4-A5

为什么?因为静态成员没有动态调度,所以声明的类型的 mySoprano1 确定哪个方法被调用...并且声明的 soprano1 的类型是 Singer ,而不是女高音



如需了解更多信息,请查看书中的拼图48我得到的都是静态的 Java Puzzlers


According to Java, static variable are accessible by Class name but they are also accessible by class object even though Java don't suggest it, and it gives the same answer.

I know there will be only one copy of the variable and its value will be same for all objects and other things. Why does Java suggest to use class name instead of class object?

解决方案

Because it can be confusing! There is no dynamic dispatching on static members.

Take a look at this confusing code: (might be syntax errors; my Java is rusty)

public abstract class Singer {
    public static void sing() {
        System.out.println("Singing");
    }
}

public class Soprano extends Singer {
    public static void sing() {
        System.out.println("Singing in the range of C4-A5");
    }
}

public class MyDriver {

    public static void main(String[] argv) {
        Singer  mySoprano1 = new Soprano();
        Soprano mySoprano2 = new Soprano();
        mySoprano1.sing();
        mySoprano2.sing();
    }

}

Looking at MyDriver it's confusing because it seems like the sing method is polymorphic so the output should be...

Singing in the range of C4-A5
Singing in the range of C4-A5

... because both soprano1 and soprano2 are instances of Soprano - not Singer.

But alas, the output is actually:

Singing
Singing in the range of C4-A5

Why? Because there is no dynamic dispatch on static members, so the declared type of mySoprano1 determines which sing method is invoked... and the declared type of soprano1 is Singer, not Soprano.

For more, check out Puzzle 48 "All I get is static" in the book Java Puzzlers.

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

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