Java:引用相同Superclass实例的子类实例

时间:2016-04-05 17:37:08

标签: java inheritance composition

在标记副本之前,请阅读:

我确实阅读了以下文章,并找到了潜在的解决方案'不是我想要的,因为大多数人使用equals()方法解决。

Classes sharing the same super class instance

我要做的是拥有多个可以共享单个父类实例的静态可访问子类实例,以便反映对父实例的更改。我对各种解决方案持开放态度,但我试图最小化对象引用的数量,并且必须以静态方式存储和调用这些实例。

希望以下代码能够更详细地解释我想要实现的目标。

// ParentClass

public class School {
    private static final HashMap<String,School> pmapping = new HashMap<>();

    private final String pname;
    private int pvalue;

    private School( String name, int value) {
        pname = name;
        pvalue = value;

        pmapping.put(name,this);
    }

    public static School build( String name, int value) {
        return this( name, value);

    public static School instance( String name) {
        // Yes there will be exception handling in the final version
        return mapping.get(name);

    public String name() {
        return pname;
    }

    public void setValue( int value) {
        pvalue = value;
    }

    public void getValue( ) {
        return pvalue;
    }
}

// ChildClass

public class Subschool extends School {
    private static final HashMap<String,Subschool> cmapping = new HashMap<>();

    private final String cname;

    private Subschool( School school, String name) {
        // what I would like to happen
        super = school;
        cname = name;

        cmapping.put( cname, this);
    }

    public static School build( String school, String name) {
        School s = School.instance(school);
        return this( s, name);

    public static School instance( String name) {
        // Yes there will be exception handling in the final version
        return cmapping.get(name);

    public String name() {
        return cname;
    }
}

// TestClass

public class Test {
    public static main(String[] args){
        // What I need to occur
        School illusion = School.build( "Illusion", 1);
        Subschool figment = Subschool.build( "Illusion", "Figment");
        Subschool shadow  = Subschool.build( "Illusion", "Shadow");

        illusion.setValue( 3);
        if( figment.getValue() == 3) 
            System.out.println( "Check 1 Succeed");
        if( figment.getValue() == shadow.getValue() )
            System.out.println( "Check 2 Succeed");
    }
}

0 个答案:

没有答案