Is it possible to declare Class in a method body

You might wonder, if its possible to declare a class in a method body.

This class can be accessed only within the Method in which it is declared.
Can access all members of outer class
Since it is inside a method, this class cannot have access specifiers
This class cannot have same name as Outer class



public class ClassInAMethod {
	public static void main(String[] args) {
	new OuterClass().display();
	}
	}

	class OuterClass {
	public void display() {
	final String s = "Test: ";
	class Rect {
	private float width;
	private float height;
	public Rect(float width,float height) { this.width=width; this.height=height; }

	//s is member of OuterClass
	public String toString() { return ""+width+","+height+s; }
	};
	System.out.println(new Rect(1.2f,2.3f));
	} // end of method print
	} // end of class OuterClass

You may also like to read:
What is anonymous inner class

One thought on “Is it possible to declare Class in a method body”

Leave a Reply