I need a object B, but i get a object A when i execute 'B.GetByID()'
public class A
{
public A()
{
}
public static A GetSelf()
{
return new A();
}
public static A GetByID()
{
return GetSelf();
}
}
public class B extends A
{
public B()
{
super();
}
public static B GetSelf()
{
return new B();
}
}
B.GetByID(); //returns A, i need B
You can only do that by also creating a B GetByID()
method in B
. That's somewhat ugly though...
Basically your B.GetByID()
call will be resolved to A.GetByID()
; nothing in the compiled code will indicate that it was originally B.GetByID()
, and the call to GetSelf()
within GetByID()
will be resolved to A.GetSelf()
anyway.
Basically, static methods don't allow for polymorphism in the way you want. I suggest you create an AFactory
and a BFactory
subclass, and use method overriding in the normal way, with instance methods.
You could add a GetByID
method to B
, like so:
public class B ... {
public static B GetByID()
{
return GetSelf();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With