Reputation: 69
I've static nested class like below
public class AbstractClass {
String AbstractClass = "AbstractClass";
AbstractClass(){
System.out.println("default constructor");
}
AbstractClass(String inp){
this.AbstractClass = inp;
System.out.println(this.AbstractClass);
}
}
-----
public class MyClass {
String MyClassVrbl = "MyClass";
public static class Builder extends AbstractClass {
String staticclassVrbl = "staticclassVrbl";
Builder() {
}
Builder(String inp) {
super(inp);
System.out.println("custom construtor");
}
}
public static void main(String[] args) {
MyClass.Builder mc = new MyClass.Builder("calling custom");
System.out.println(mc.how can access outer class instance variable..?);
}
}
Once nested class(Builder) instance is created, parent(MyClass
) must be instantiated too..right ? How can I access outer class instance out of mc
to access MyClassVrbl
?
Is isnt it strange if MyClass
is not instantiated even after creating nested Builder
class ?
Upvotes: 2
Views: 153
Reputation: 72844
Once nested class(Builder) instance is created, parent(MyClass) must be instantiated too..right ?
That's not the case because the nested class is static. If it were an inner non-static class, then there would be an instance of the outer class associated with it. So the answer is you can't get the outer instance because it does not exist.
Static nested class:
public class MyClass {
public static class Builder {
Builder() {
MyClass outerInstance = MyClass.this; // does not compile
}
}
}
Non-static nested class (aka inner class):
public class MyClass {
public class Builder {
Builder() {
MyClass outerInstance = MyClass.this; // ok
}
}
}
Besides, when using the builder pattern you probably want to access the created instance using a build()
method.
Upvotes: 1
Reputation: 9284
You can't access myClassVrbl
using mc
, because mc
is an object of Builder
which is a subclass of AbstractClass
. You can access members of AbstractClass
, but not of MyClass
. Instantiating a Builder
class object calls its super class constructor, not the one within which it is nested.
Upvotes: 0