我一直在SCJP学习指南中阅读有关Statics的部分,它提到了以下内容:
静态方法不能被覆盖,但可以重新定义它们
重新定义实际意味着什么?是否存在父和子都存在的静态方法,具有相同的签名,但是它们的类名分别引用它们?如 :
class Parent
{
static void doSomething(String s){};
}
class Child extends Parent
{
static void doSomething(String s){};
}
Run Code Online (Sandbox Code Playgroud)
引用为:Parent.doSomething();
和Child.doSomething();
?
此外,这同样适用于静态变量,还是静态方法?
Mat*_*arz 17
它只是意味着功能不是虚拟的.例如,假设您有一个(运行时)类型的对象Child,它是从Parent类型的变量引用的.然后,如果您调用doSomething
,doSomething
则调用Parent 的方法:
Parent p = new Child();
p.doSomething(); //Invokes Parent.doSomething
Run Code Online (Sandbox Code Playgroud)
如果方法是非静态的,doSomething
则Child将覆盖Parent的方法,并且child.doSomething
将被调用.
静态字段也是如此.
静态意味着每个类有一个,而不是每个对象一个.对于方法和变量都是如此.
静态字段意味着存在一个这样的字段,无论该类创建了多少个对象.请看一下有没有办法在Java中覆盖类变量?关于覆盖静态字段的问题.简而言之:无法覆盖静态字段.
考虑一下:
public class Parent {
static int key = 3;
public void getKey() {
System.out.println("I am in " + this.getClass() + " and my key is " + key);
}
}
public class Child extends Parent {
static int key = 33;
public static void main(String[] args) {
Parent x = new Parent();
x.getKey();
Child y = new Child();
y.getKey();
Parent z = new Child();
z.getKey();
}
}
I am in class tools.Parent and my key is 3
I am in class tools.Child and my key is 3
I am in class tools.Child and my key is 3
Run Code Online (Sandbox Code Playgroud)
密钥永远不会返回33.但是,如果重写getKey并将其添加到Child,则结果将不同.
@Override public void getKey() {
System.out.println("I am in " + this.getClass() + " and my key is " + key);
}
I am in class tools.Parent and my key is 3
I am in class tools.Child and my key is 33
I am in class tools.Child and my key is 33
Run Code Online (Sandbox Code Playgroud)
通过重写getKey方法,您可以访问Child的静态密钥.