Reputation: 61
I there,
I have this scenario:
public class A{
//attributes and methods
}
public class B{
//attributes and methods
}
public class C{
private B b;
//other attributes and methods
}
public class D{
private C c1, c2, c3;
private List<A> a;
//other attributes and methods
}
Every class has its own file. However, I'd like to get classes A, B and C as inner classes of class D because I'm not using them throughout the program, just in a small part of it. How should I implement them? I've read about it, but I'm still not sure about what is the best alternative:
Option 1, using static classes:
public class D{
static class A{
//attributes and methods
}
static class B{
//attributes and methods
}
static class C{
private B b;
//other attributes and methods
}
private C c1, c2, c3;
private List<A> a;
//other attributes and methods
}
Option 2, using an interface and a class that implements it.
public interface D{
class A{
//attributes and methods
}
class B{
//attributes and methods
}
class C{
private B b;
//other attributes and methods
}
}
public class Dimpl implements D{
private C c1, c2, c3;
private List<A> a;
//other attributes and methods
}
I'd like to know which approach is better in order to get the same behavior using the original scenario. Is it ok if I use Option 1 and use the classes like this?
public method(){
List<D.A> list_A = new ArrayList<D.A>();
D.B obj_B = new D.B();
D.C obj_C1 = new D.C(obj_B);
D.C obj_C2 = new D.C(obj_B);
D.C obj_C3 = new D.C(obj_B);
D obj_D = new D(obj_C1, obj_C2, obj_C3, list_A);
}
Basicly, my concern is how the creation of inner classes will affect the outter class. In the original scenario, I first create the instances of classes A, B and C, then the instance of class D. Can I do the same with the options I mentioned?
Upvotes: 3
Views: 292
Reputation: 33544
Inner Classes are of 2 Types:
Static Inner Classes (Known as Top Level Classes)
Inner Classes
Static Inner Class Example:
public class A {
static int x = 5;
int y = 10;
static class B {
A a = new A(); // Needed to access the non static Outer class data
System.out.println(a.y);
System.out.println(x); // No object of outer class is needed to access static memeber of the Outer class
}
}
Inner Class Example:
public class A {
int x = 10;
public class B{
int x = 5;
System.out.println(this.x);
System.out.println(A.this.x); // Inner classes have implicit reference to the outer class
}
}
To create an objec of the Inner Class (NOT STATIC INNER CLASS), from outside, the outer class objec is needed to be created first.
A a = new A();
A.B b = a.new B();
Upvotes: 0
Reputation: 137442
If you are only going to use them inside the class, you have no reason to use interface, as interface is intended for public
access. Use your first approach (and make the classes private static)
Upvotes: 6