わかりました..だから、次のようなクラスの階層がある場合
public class A {...}
と、
public class B extends A {...}
...オブジェクトを作成するときの違いは何ですか:
A object = new A();
A object = new B();
B object = new B();
お時間をいただきありがとうございます。
わかりました..だから、次のようなクラスの階層がある場合
public class A {...}
と、
public class B extends A {...}
...オブジェクトを作成するときの違いは何ですか:
A object = new A();
A object = new B();
B object = new B();
お時間をいただきありがとうございます。
public class A
{
public void methodA(){}
}
public class B extends A
{
public void methodB(){}
}
I hope this can demonstrate the difference.
A obj = new A();
a.methodA(); //works
A obj = new B();
obj.methodA(); //works
obj.methodB(); //doesn't work
((B)obj).methodB(); //works
B obj = new B();
obj.methodA(); //works
obj.methodB(); //works
A object = new A();
タイプ A の参照でを作成しA instance
ています。アクセスできるのは、A メソッド/プロパティおよび親メソッド/プロパティのみです。
A object = new B();
タイプ A の参照で作成 B instance
しています。この方法object
では、多態的な方法で動作する可能性があります。たとえば、作成して B でオーバーライドされた場合、object.method()
このmethod
オーバーライド メソッドが呼び出されます。Liskov Substitution Principleを破らないように注意する必要があります。A メソッド/プロパティおよび親メソッド/プロパティのみにアクセスできます。これは、スーパータイプ コントラクトのみが必要な場合に推奨される方法です。
B object = new B();
B instance
タイプ の参照変数に を作成していますB
。B メソッド/プロパティおよび親メソッド/プロパティのみにアクセスできます。
A object = new B();
This declares that object
will refer to an object of class A
or any of its subclasses (when it isn't null
). The compiler will treat it as an object of type A
, so you can only access methods and fields that are declared for A
(or one of its superclasses). It also means that you can later assign it to any other object that is of class A
or a subclass:
A object1 = new B();
B object2 = new B();
// reassign later
object1 = new A(); // legal
object2 = new A(); // ILLEGAL
class C extends A { ... }
object1 = new C(); // legal
object2 = new C(); // ILLEGAL
So the initial declaration declares object
as having type A
. But its initial value is an object of type B
, which is OK because B
is a subclass of A
.
That should explain the difference between your second and third examples. The difference between the first and second is simply that (at run time) the first creates a new object of type A
and the second creates a new object of type B
.
A object = new A();
object
型A
( からフィールドまたはメソッドにアクセスできますA
)
A object = new B();
object
型A
( からはフィールドまたはメソッドにアクセスできません。 からB
のみアクセスできますA
)
B object = new B();
object
型(およびB
からフィールドまたはメソッドにアクセスできます)A
B
A object1 = new A();
A object2 = new B();
B object3 = new B();
object1
A オブジェクトへの参照として宣言されます。クラス B はクラス A を拡張するため、または (new A()
またはnew B()
有効) のいずれかに設定できます。
object2
A オブジェクトへの参照として宣言されていますが、実際には B オブジェクトです。B クラスに というメソッドがあるとしeatFood()
ます。そのメソッドに でアクセスしようとするとobject2.eatFood()
、eatFood メソッドは B クラスだけにあるため、コンパイラはエラーをスローします。オブジェクトは実際には B オブジェクトですが、型宣言により、コンパイラはそれを A オブジェクトと見なします。eatFood メソッドにアクセスするには、次のように型キャストする必要があります((B)object2).eatFood()
。
object3
は単に B オブジェクトへの参照であり、実際には IS は B オブジェクトです。A メソッドだけでなく B メソッドにもアクセスできます。