12

SCJPスタディガイドのStaticsに関するセクションを読んでいて、次のことが言及されています。

静的メソッドはオーバーライドできませんが、再定義できます

再定義とは実際には何を意味するのでしょうか。親と子の両方に同じ署名を持つ静的メソッドが存在する場合ですが、それらはクラス名によって個別に参照されますか? そのような :

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

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

として参照:Parent.doSomething();Child.doSomething();?

また、同じことが静的変数、または静的メソッドにも当てはまりますか?

4

3 に答える 3

17

これは単に、関数が仮想ではないことを意味します。例として、Parent 型の変数から参照される (実行時) Child 型のオブジェクトがあるとします。次に を呼び出すと、ParentdoSomethingのメソッドが呼び出されます。doSomething

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

メソッドが静的でない場合、doSomethingChild は Parent のメソッドをオーバーライドし、child.doSomething呼び出されます。

同じことが静的フィールドにも当てはまります。

于 2011-07-07T11:32:18.117 に答える
6

静的とは、オブジェクトごとではなく、クラスごとに 1 つあることを意味します。これは、メソッドと変数の両方に当てはまります。

静的フィールドは、そのクラスのオブジェクトがいくつ作成されても、そのようなフィールドが 1 つあることを意味します。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 の回答では、親と子の両方で 2 つのメソッドを静的にする場合:

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

ここで注意すべき 2 つの点: 「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
于 2013-03-25T06:43:02.427 に答える