[JAVA] About Enclosing Instance 2

I actually tried to practice the enclosing instance

Is it like this for the time being? I thought about it.


public class Outer {
	String outerName = "outer";
	
	public static void main(String[]args) {
		Outer outer = new Outer();
		Inner inner = outer.new Inner();
		System.out.println(Outer.outerName);////
	}
	public class Inner{
		
	}
}

The /// part was an error. It was said that non-static Outer class fields cannot be called from the static main method, so it has been improved.


public class Outer {
	String outerName = "outer";

	public static void main(String[]args) {
		Outer outer = new Outer();
		Inner inner = outer.new Inner();
		inner.outerAccess();
	}
	public class Inner{
		void outerAccess() {
			System.out.println(outerName);
		}
	}
}

Call outer.name, which is a member of the non-static inner class Inner class and the non-static outer class (Outer). Then, by creating an instance of the Inner class included in the instance of the Outer class with the main method and calling the outerAccess method of the Inner class, the error disappeared (is it the outerAccess method of the Inner instance?).

You can call it by outer.outerName in the first place, right? I thought and tried it

public class Outer {
	String outerName = "outer";

	public static void main(String[]args) {
		Outer outer = new Outer();
		Inner inner = outer.new Inner();
		inner.outerAccess();
		System.out.println(outer.outerName);
	}
	public class Inner{
		void outerAccess() {
			System.out.println(outerName);
		}
	}
}

I was able to call. I learned that there are various ways to call

Recommended Posts

About Enclosing Instance 2
About Ruby instance methods
About calling instance methods
[Ruby] About instance generation
I investigated the enclosing instance.
About an instance of java
About =
About instance variables and attr_ *
About method.invoke
About Kotlin
About attr_accessor
About Hinemos
About inheritance
About params
About Docker
About Rails 6
About form_for
About Spring ③
About enum
About polymorphism
About hashes
About JitPack
About this ()
About devise
About encapsulation
About Docker
About active_hash
About static
About exceptions
About scope
Find out about instance methods and self
[Maven] About Maven
No enclosing instance of type Hoge is accessible.