Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i use the same factory method for a subclass?

Tags:

java

factory

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
like image 967
user844674 Avatar asked Dec 13 '22 11:12

user844674


2 Answers

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.

like image 66
Jon Skeet Avatar answered Dec 21 '22 22:12

Jon Skeet


You could add a GetByID method to B, like so:

public class B ... {

    public static B GetByID()
    {
        return GetSelf();
    }

}
like image 41
NPE Avatar answered Dec 21 '22 23:12

NPE