Java Basic Problems

Java: Static Class

About  Static Class:

Static Class is that class in Java for which we don’t need to create any Object.

Though we can create an object of a static class  but it is meaningless, we can use the members and methods of Static Class without creating an Object . The variables and methods can be used by calling them using class name only

Some Important Notes:

** A static nested class uses the instance variables (not static variables) / methods declared or defined in its enclosing class only by using an object reference.  

Code:

public class StaticVariable1

{

static int demo=0;

 StaticVariable1()

{

NonStaticClass demo1=new NonStaticClass();

System.out.println(“Before Value Change in NonStaticClass i=”+demo1.getValue());

demo1.i=10;

System.out.println(“After Value Change in NonStaticClass i=”+demo1.getValue());

}

static class StaticClass

{

static int i=0;

static int j;

}

public class NonStaticClass

{

int i;

int j;

public int getValue()

{

return i;

}

}

public static void main(String[] args)

{

System.out.println(“Before Value Change in StaticClass i=”+StaticClass.i);

StaticClass.i=10;  // No need to Create Object to initialize value of variable i in StaticClass

System.out.println(“After Value Change in StaticClass i=”+StaticClass.i);

//NonStaticClass.i=10; *** check below

StaticVariable1 demo=new StaticVariable1(); 

}

}

** It will create error   non-static variable i cannot be referenced from a static Context NonStaticClass.i=10;

                          ^

OUTPUT:

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s