12

我一直在阅读 SCJP 学习指南中有关静态的部分,其中提到了以下内容:

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

重新定义实际上意味着什么?是否有一个静态方法存在于父级和子级中,具有相同的签名,但是它们由它们的类名单独引用?如 :

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

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

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

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

4

3 回答 3

17

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

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

如果方法是非静态的,doSomething则 Child 将覆盖 Parent的方法child.doSomething并被调用。

静态字段也是如此。

于 2011-07-07T11:32:18.117 回答
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

Key 永远不会返回为 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 的静态密钥。

于 2011-07-07T12:15:50.500 回答
0

在 rajah9 的回答中,如果现在我们在父子节点中将这两个方法设为静态:

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

现在要注意两件事:不能使用“this.getClass()”和警告“父类型的静态方法 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
于 2013-03-25T06:43:02.427 回答