-1

At the top of my class hierarchy is the class Mammal. Each instance of Mammal is required to statically initialize itself. (The example is silly, I know. If you are curious, I am using Android fragments and I cannot override their constructors)

For example:

public abstract class Mammal{
    private static initialize(int a, String b, ...){
        ...
    }  
}

public class Dog extends Mammal{
    public static Dog newInstance(int a, String b, ...){
        Dog dog = new Dog();
        initialize(a, b, ...);
    }
}

public class Cat extends Mammal{
    public static Cat newInstance(int a, String b, ...){
        Cat cat = new Cat();
        initialize(a, b, ...);
        return cat;
    }
}

The classes could continue indefinitely. I have looked into calling a subclass constructor from a superclass but I cannot figure out how to apply it to a static context. Thanks in advance!

Community
  • 1
  • 1
Daiwik Daarun
  • 3,804
  • 7
  • 33
  • 60

2 Answers2

1

The initialize method should have a the a Mammal as parameter to initialize it's data from the other parameters:

  private static initialize(Mammal mammal, int a, String b, ...){
     mammal.setA(a)
     // ...
 }  
Jonatan Cloutier
  • 899
  • 9
  • 26
1

From Oracle Java Docs

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

It is better explained at here Overriding vs Hiding Java - Confused

To access child class's method you need to call the method with reference of the subclass

Mamal mamal = new Dog();
mamal.initialize(..) // method of super class
((Dog)mamal).initialize(...)// method of class dog  
Community
  • 1
  • 1
mirmdasif
  • 6,014
  • 2
  • 22
  • 28