pepin
pepin

Reputation: 23

Subinstances sharing a common superinstance

I have a class Super and several subclases Sub1, Sub2,...

Is there a way to instantiate objects sub1, sub2 that would share the same super instance?

The situation comes from an inner nested class configuration like this:

Super{  
    superFields...
    Sub1{...}
    Sub2{...}
    ........
    }

But the inner claeses have grown too much, and I woud feel more confortable having them in separate files. They need to share the same instance of superFields, so my question.

Upvotes: 2

Views: 107

Answers (2)

akf
akf

Reputation: 39485

You could easily break out your inner classes and have each of them reference an instance of the current containing class. When you construct your new classes, you can pass in the same instance to both, and then the new classes can use the accessors to get at the fields of the containing class.

class Super {
    String fieldA;
    int fieldB;
    ...
}

in your new files, something like the following:

class Sub1{
    Super myOldContainingClass;
    Sub1(Super myOldContainingClass) {
        this.myOldContainingClass = myOldContainingClass;
    }

    void myMethod() {
        System.out.println(myOldContainingClass.getFieldA());
        System.out.println(myOldContainingClass.getFieldB());
    }
}

Upvotes: 2

Bozho
Bozho

Reputation: 597076

Inner classes are implemented by having the superclass as argument of all their constructors.

So that's what you can do as well:

public class Sub1 {
   private Superclass superclass;
   public Sub1(Superclass superclass) {
       this.superclass = superclass;
   }
}

and whenever you want to instantiate the subclass from within the superclass:

Sub1 sub = new Sub1(this);

Upvotes: 2

Related Questions