简体   繁体   中英

How to access Outer class Instance?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM