在Java中,重新定义静态方法的含义是什么?

12

我一直在阅读SCJP学习指南中关于静态方法的部分,其中提到:

静态方法无法被覆盖,但可以被重新定义

重新定义实际上是什么意思?这是指在父类和子类中都存在具有相同签名的静态方法,但它们通过各自的类名称分别引用吗?例如:

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

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

如下引用:Parent.doSomething();Child.doSomething(); ,这是什么意思?

同样的规则适用于静态变量吗,还是只适用于静态方法?

3个回答

17

这意味着这些函数不是虚函数。比如,假设你有一个运行时类型为 Child 的对象,并且这个对象被引用到了一个类型为 Parent 的变量中。那么如果你调用 doSomething 方法,将会调用 Parent 类的 doSomething 方法:

Parent p = new Child();
p.doSomething(); //Invokes Parent.doSomething
如果这些方法不是静态的,那么Child类的doSomething会覆盖Parent类的相应方法,调用child.doSomething时会执行Child类的方法。
对于静态字段也是一样的。

6

静态意味着每个类只有一个,而不是每个对象都有一个。这对方法和变量都是正确的。

静态字段意味着无论创建多少个该类的对象,都只有一个这样的字段。请参阅在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类的静态键。

0
在rajah9的回答中,如果我们现在将父类和子类的两个方法都设置为静态的:
public static void getKey() {
        System.out.println("I am in and my key is " + key);
    }

现在需要注意两件事情: 不能使用'this.getClass()',并且会出现警告'The static method getKey() from the type Parent should be accessed in a static way'

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接