views:

30

answers:

2

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.

+2  A: 

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());
    }
}
akf
I see, you mean using composition.I would have preferred a direct acces to parent members -like in the nested class configuration- as there are many members to be accessed and don't like to clutter the code too much.But I'm affraid this is not going to be possible with inheritance, so I'll have to choose between the current nested class aproach or the composition one that you mentioned. Thanks
pepin
+2  A: 

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);
Bozho
Very clever! I have to replicate all parent members in each sub class but the code will be cleaner as I don't have to use accesors everywhere. So this is in fact a dissasambled inner class!!. I didn't know. Thanks
pepin
@pepin - if one of the answers suits you, then you are supposed to mark it as accepted (the tick below the vote counter)
Bozho
OK, I didn't know
pepin