在Java中重新定义静态方法意味着什么?

我一直在阅读SCJP学习指南中关于静力学的一节,它提到了以下内容:

静态方法不能被覆盖,但可以重新定义它们

重新定义实际意味着什么? 是否存在父和子都存在的静态方法,具有相同的签名,但是它们的类名分别引用它们? 如 :

class Parent { static void doSomething(String s){}; } class Child extends Parent { static void doSomething(String s){}; } 

引用为: Parent.doSomething();Child.doSomething();

此外,这同样适用于静态变量,还是静态方法?

它只是意味着function不是虚拟的。 例如,假设您有一个(运行时)类型的对象Child,它是从Parent类型的变量引用的。 然后,如果调用doSomething ,则调用Parent的doSomething方法:

 Parent p = new Child(); p.doSomething(); //Invokes Parent.doSomething 

如果这些方法是非静态的,那么doSomething of 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 

密钥永远不会返回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 

通过重写getKey方法,您可以访问Child的静态密钥。

在rajah9的回答中,如果现在我们在父和子中使这两个方法都是静态的:

 public static void getKey() { System.out.println("I am in and my key is " + key); } 

现在要注意两件事:不能使用’this.getClass()’和警告’来自类型Parent的静态方法getKey()应该以静态方式访问’

 Parent z = new Child(); z.getKey(); 

会给出输出

 I am in class tools.Parent and my key is 3 

代替

 I am in class tools.Parent and my key is 33