Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes sharing the same super class instance

Tags:

java

I have a very simple question.

Can 2 classes share the same Super class instance? I know the answer is no, because super is the instance itself, but I was really there was some workaround...

public class Parent{
    private final int parentId;
    private static final HashMap<Integer,Parent> parentMap = new HashMap<Integer,Parent>();

    private Parent(int i){
       parentId = i;
       parentMap.put(i,this);
    }

    public static Parent newInstance(int i)
    {
        if(parentMap.containsKey(i))
            return parentMap.get(i);

        return new Parent(i);

    }
}

/* Other class */

public class ExtendedParent extends Parent{
    public ExtendedParent(int i){
        super(i);//I should use the factory at this point...
    }

    public static main(String[] args){
        /*What I am trying to achieve*/
        Parent p1 = new ExtendedParent(1);
        Parent p2 = new ExtendedParent(1);

        if(p1.equals(p2))
            System.out.println("This is what i aim to get!!!!");

    }
}

Remade the code to demonstrate my problem clearly.

Can someone help me out? =D

Thanks in advance!

like image 423
matutano Avatar asked Sep 01 '25 10:09

matutano


2 Answers

I see two alternatives:

  • Make the relevant parent's attributes and methods static, so that they are shared among all descendants.
  • Replace the parent class with an interface and share an attribute of the original parent class between subclass instances.
like image 129
Nicola Musatti Avatar answered Sep 03 '25 00:09

Nicola Musatti


Make ExtendedParent instances forward calls to a Parent instance they keep as a member. And methods that should not only forward the calls, add the additional processing that distinguishes ExtendedParent from Parent.

like image 30
Adrian Panasiuk Avatar answered Sep 03 '25 00:09

Adrian Panasiuk