Static Java
Static Java
We
can apply static keyword with variables, methods, blocks and nested classes.
The static keyword belongs to the class than an instance of the class.
o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the
company name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time
of class loading.
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }
Suppose there are 500 students in my college, now all instance data
members will get memory each time when the object is created. All students
have its unique rollno and name, so instance data member is good in such
case. Here, "college" refers to the common property of all objects. If we
make it static, this field will get the memory only once.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an
instance of a class.
o A static method can access static data member and can change the
value of it.
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-
static method directly.
2. this and super cannot be used in static context.
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6.
Since JDK 1.7, it is not possible to execute a Java class without the main
method.
1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Java static nested class
A static class is a class that is created inside a class, is called a static nested
class in Java. It cannot access non-static data members and methods. It can
be accessed by outer class name.
o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members or
1. class TestOuter{
2. static int data=30;
3. static class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter.Inner obj=new TestOuter.Inner();
8. obj.msg();
9. }
10.}
In this example, you need to create the instance of static nested class because it
has instance method msg(). But you don't need to create the object of the Outer
class because the nested class is static and static properties, methods, or classes
can be accessed without an object.
TestOuter2.java