简体   繁体   English

简化类层次结构中的代码

[英]Simplifying code in a class hierarchy

At the top of my class hierarchy is the class Mammal . 我班级的最上层是Mammal Each instance of Mammal is required to statically initialize itself. 需要Mammal每个实例进行静态初始化。 (The example is silly, I know. If you are curious, I am using Android fragments and I cannot override their constructors) (我知道这个例子很愚蠢。如果您很好奇,我正在使用Android片段,并且无法覆盖它们的构造函数)

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! 提前致谢!

The initialize method should have a the a Mammal as parameter to initialize it's data from the other parameters: initialize方法应具有一个Mammal作为参数,以从其他参数初始化其数据:

  private static initialize(Mammal mammal, int a, String b, ...){
     mammal.setA(a)
     // ...
 }  

From Oracle Java Docs 从Oracle Java文档

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 在此处更好地解释覆盖与隐藏Java-混淆

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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM