Class inside a Method ? Is it possible ?… Yes, Possible…

Hi Friends,
Here we are going to create a class inside a method, and , a class in a method is called Local Class.

In the following code, we have created a class “LocalClass” within “show()” method and then have a “displayVal()” Method inside LocalClass.

Well, to access members of a local class, we have to create an instance of local class within that method in which it is defined.

class MyClass {void show(){
class LocalClass{
int val = 50;
void displayVal(){
System.out.println(“Val = ” + val);
}LocalClass l = new LocalClass();
public static void main(String[] args) {

MyClass m1 = new MyClass();;

Here, we are creating an instance of LocalClass within show() method because this class is defined in this method.

and finally calling show() method from main() method of our class.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s