Java - Static Feature Examples
package javaPrograms;
public class StaticMemoryManagement {
int a =20;
static int b = 30;
void add() {
a=a+20;
b=b+20;
System.out.println("a is "+a);
System.out.println("b is "+b);
}
static {
System.out.println("static block is invoked before main method");
}
static void staticMethod() {
System.out.println("static method would be called without need of creating object of a class");
}
void nonStaticMethod() {
System.out.println("test"+b); // Static members are accessible directly by non static methods within class
}
public static void main(String args[]) {
StaticMemoryManagement obj1 = new StaticMemoryManagement();
obj1.add();
StaticMemoryManagement obj2 = new StaticMemoryManagement();
obj2.add();
StaticMemoryManagement.staticMethod(); // It also works
staticMethod(); // This also works
obj1.nonStaticMethod();
System.out.println(b); // Static data members are accessible directly by static methods within same class
System.out.println(obj1.a); // Non static members are accessible through objects only
}
}
package javaPrograms;
public class StaticMemoryManagement {
int a =20;
static int b = 30;
void add() {
a=a+20;
b=b+20;
System.out.println("a is "+a);
System.out.println("b is "+b);
}
static {
System.out.println("static block is invoked before main method");
}
static void staticMethod() {
System.out.println("static method would be called without need of creating object of a class");
}
void nonStaticMethod() {
System.out.println("test"+b); // Static members are accessible directly by non static methods within class
}
public static void main(String args[]) {
StaticMemoryManagement obj1 = new StaticMemoryManagement();
obj1.add();
StaticMemoryManagement obj2 = new StaticMemoryManagement();
obj2.add();
StaticMemoryManagement.staticMethod(); // It also works
staticMethod(); // This also works
obj1.nonStaticMethod();
System.out.println(b); // Static data members are accessible directly by static methods within same class
System.out.println(obj1.a); // Non static members are accessible through objects only
}
}
Output :
static block is invoked before main method
a is 40
b is 50
a is 40
b is 70
static method would be called without need of creating object of a class
static method would be called without need of creating object of a class
test70
70
40
No comments:
Post a Comment