2011-07-07 6 views
12

私はSCJP研究ガイドで静のセクションを読んでいると、それは次のように言及している:Javaでは静的メソッドの再定義は何を意味しますか?

静的メソッドは、上書き 彼らは

何を再定義することができますすることができません再定義は実際にはどういう意味ですか?親と子の両方に同じシグネチャを持つ静的メソッドを持つケースですが、クラス名で別々に参照されていますか?以下のような:Parent.doSomething();Child.doSomething();:として参照

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

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

また、静的変数または静的メソッドに対しても同じことが適用されますか?

答えて

17

単に機能が仮想ではないことを意味します。たとえば、Parent型の変数から参照される(実行時)型のChildというオブジェクトがあるとします。あなたがdoSomethingを起動する場合はその後、親のdoSomethingメソッドが呼び出されます。

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

方法は非静的であれば、子供のdoSomethingは親のことを無効になり、child.doSomethingが呼び出されていたであろう。

静的フィールドも同じです。

6

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

静的なフィールドは、そのクラスのオブジェクトがいくつ作成されても、そのようなフィールドが1つあることを意味します。静的フィールドのオーバーライドについては、Is there a way to override class variables in 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 

キーは、あなたがのgetKeyをオーバーライドして、子供にこれを追加した場合、その結果は異なるだろう、しかしバック33のように来ることはありません。 getKeyメソッドをオーバーライドすることで

@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 

、あなたは子供の静的なキーにアクセスすることができます。 「 「はthis.getClass()」と警告を使用することはできません。今、注目すべき

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

2つのこと:rajah9の答えで

0

は、我々は両方の親と子の静的の2つのメソッドを作るになりました場合には静的な方法でアクセスされなければならない型の親から静的メソッドの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 
関連する問題