Monday, May 26, 2014

# 15 - STATIC made SIMPLE

Hello,

In my starting days of programming I tried to understand the use of static keyword in Java. I googled about it, I discussed with my seniors to exactly understand what is all about this BIG guy static. Yes, I call this modifier as a BIG guy coz it is not like any other modifier in Java. It is different that’s what makes him special..!! In this post I am gonna make this BIG guy really simple for you to understand so that you guys can get it in ONE reading..! That’s the only motto of my blog..! J

static

This modifier can be used with classes/methods/variables. As a basic definition, before we go into the details, static modifier makes classes/methods/variables static..!! That’s it..! :P

Yea. I am explaining. Static means not instance specific. Class Specific. The first time we instantiate the class, all the static variables/methods gets instantiated. And later if you create 1000 instances, the value static variables/methods do not change.  You can see this in programming below so that you understand better. I know you guys understand better in Programming language than English.!

Btw, I wanna add one more point. Many people get confused about class members and instance members in Java.
The methods/variables which are declared as static --> are Class members
The methods/variables which are NOT declared as static --> are Instance members.

Static modifier with classes

Yes, static modifier can be used with classes. ONLY WITH INNER CLASSES. If you try to put the static modifier before a base class (top level class), the compiler will start shouting at you.
public static class ClassA{
	
	public static void main(String... args){
		
		// your code and logic for this method goes here. 
	}
}
I have a class ClassA which is the only class in the file. I declared the class as static and when I tried to compile the class, I get the below error.
Illegal modifier for the class ClassA; only public, abstract & final are permitted
You knew it. Classes can have ONLY public, abstract or final modifiers. It cannot accept any other modifier.

Let us see with inner classes.
public class ClassA{
	
	public static void main(String... args){
		
		System.out.println("ClassA.main()");
		
		// create an instance of Inner class ClassB
		ClassB b = new ClassB();
		
		// retrieve the value of ClassB instance variable i 
		System.out.println("ClassA.main().. instance variable i --> "+b.i);
		
		// retrieve the value of ClassB class variable j
		System.out.println("ClassA.main().. class variable j --> "+ClassB.j);
		
	}
		
	// Inner class
	static class ClassB{
		
		//instance vaiable
		int i = 10;
		
		// static variable
		static int j = 20;
		
	}
}
}

When I try to compile the above class, I get,
Output:
ClassA.main()
ClassA.main().. instance variable i --> 10
ClassA.main().. class variable j --> 20
  • Static nested(inner) classes are allowed. There is no such thing called static top-level class in Java.
  • If an inner class is declared as static, it doesn't mean that it should necessarily contain ONLY static methods/variables. It can also contain non-static members.
  • For accessing non-static members of an inner class, we need to create an instance of that class. But for accessing static members, we just need to use InnerClassName.StaticMember.

So here comes the BIG question, WHY ?
Why a top-level class is not allowed to declare as static when an inner class is allowed?

Top-level class is not allowed to declare as static bcoz it doesn’t make any sense..! static keywords says to the compiler that, “I do not need any instance. I can instantiate myself..!” But if a class doesn’t require any instances then what is the use of a class in an Object Oriented Programming ?  No sense - no use.

In the case of inner classes, static keyword helps us to use the static inner class without creating an instance of the outer class. If we do not use the static keyword for the inner classes, then we need to create instance of the outer class and then use this instance, we need to create the instance of non-static inner class.
public class ClassA{
	
	public static void main(String... args){
		
		System.out.println("ClassA.main()");
		
		// create an instance of Inner class ClassB
		ClassB b = new ClassB();
		
		// retrieve the value of ClassB instance variable i 
		System.out.println("ClassA.main().. instance variable i --> "+b.i);
		
		// retrieve the value of ClassB class variable j
		System.out.println("ClassA.main().. class variable j --> "+ClassB.j);
		
	}
		
	// Inner class
	static class ClassB{
		
		//instance vaiable
		int i = 10;
		
		// static variable
		static int j = 20;
		
	}
}

Static modifier with Methods/Variables

The static modifier works in the same way with the methods and variables. The first question comes why and when we have to use static keywords with methods/variables.

As I have already mentioned that the static members are class specific, so if we would like to make the methods/variables work irrespective of the class state or value of the instance members then declare that method/variable as static. 

In real time, we mostly declare the utility methods as static. Coz the utility methods should work in same way irrespective of the instance we create or the values we pass.
Assume that I have a requirement of counting the instances of my class that are being created. In this case I cannot use the instance members as they are assigned default values every time we create an instance.
public class ClassA{
	
	// class member
	static int staticCount = 0;
	
	// instance member
	int nonStaticCount = 0;
	
	// constructor
	public ClassA(){
		
		// increment by 1 every time we create an instance
		staticCount += 1;
		nonStaticCount +=1;
	}
	
	public static void main(String... args){
		
		// instance 1
		ClassA a = new ClassA();
		
		System.out.println("ClassA.main()..staticCount --> "+staticCount);
		System.out.println("ClassA.main()..nonStaticCount --> "+a.nonStaticCount);
		
		// instance 2
		ClassA aa = new ClassA();
		System.out.println("ClassA.main()..staticCount --> "+staticCount);
		System.out.println("ClassA.main()..nonStaticCount --> "+aa.nonStaticCount);
		
	}
}
When I run the above program, I get the output as
Output:
ClassA.main()..staticCount --> 1
ClassA.main()..nonStaticCount --> 1
ClassA.main()..staticCount --> 2
ClassA.main()..nonStaticCount --> 1
You can see that I have created 2 variables. One is static and the other is Non-static. For my requirement only static variable gives me the correct count. When instance 1 is created both the variables staticCount and nonStaticCount are incremented by one. When the instance 2 is created, the nonStaticCount variable is assigned to its default value zero, but the static variable staticCount value is already 1(bcoz of instance 1) and again it is incremented by 1 so that makes its value 2 and nonStaticCount value 1.
Now you may be wondering why I have used the nonStaticCount variable with the object “a” and “aa” where I have used staticCount variable directly. Right?
Bcoz, in Java we CANNOT access non-static members from a static method. If we try to do so, we get a compiler error saying,
Cannot make a static reference to the non-static field nonStaticCount
If you observe in the above program, main() method  is declared as static and so we can access static members directly in a static method. Hence I can use the staticCount variable directly in the main(). But when I want to use non-static members inside a static method, I need to create an object of a class to access its members. That is the reason I have accessed the nonStaticCount variable using a.nonStaticCount and aa.nonStaticCount


Access Static Members

We know that we don’t need to have an instance for accessing static members. Then how can we invoke or access the static members?
It’s the same DOT operator that we access the instance members with an object. But with static members we need to use ClassName.StaticMember
public class ClassA{
	
	// class member
	static int staticCount = 20;
	
	// Inner Class
	static class InnerClassA{
		public static void main(String... args){
			
			System.out.println("ClassName DOT StaticMember --> "+ClassA.staticCount);
		}
	}
}
We can also access static members using the object/instance of the class. But it is not suggested bcoz there may be a chance of not having any instances of the class at all..! So always access the static members with the class name.
public class ClassA{
	
	// class member
	static int staticCount = 20;
	
	// Inner Class
	static class InnerClassA{
		public static void main(String... args){
			
			// GOOD
			System.out.println("ClassName DOT StaticMember --> "+ClassA.staticCount);
			
			// BAD..! NOT SUGGESTED
			ClassA a = new ClassA();
			System.out.println("Using the object of Class A --> "+a.staticCount);
		}
	}
}
The above program runs perfectly without any errors.

The last point about static keyword is, static methods CANNOT be overridden but re-defined..!!
public class ClassA{
	
	// class member
	static void printString(){
		System.out.println("ClassA.printString()");
	}
}

class ClassB extends ClassA{
	
	// this is NOT allowed, bcoz static methods canNOT be overriden
	void printString(){
		System.out.println("ClassB.printString()");
	}
	
	
	// this is allowed, bcoz if we define the method here with static then it becomes the member of ClassB
	// something like we are re-defining the method. NOT overriding..!
	static void printString(){
		System.out.println("ClassB.printString()");
	}
}
static keyword shows a huge impact on the methods/variables that are declared as static, mostly when multiple users trying to access your application at a time. So make sure you use it with care..!

transient

transient is the keyword mostly associated with Serialization concept.

Serialization – is the process of streaming the objects or data into bytes before transferring to other networks.
De-Serialization – is a reversal process. Converting the byte stream data to objects.

transient keyword comes into the picture when we don’t like to serialize a particular property of an object.

Imagine I have a class Student. It has 3 properties Id, Name and Roll Number. I want to serialize the student details except studentId. In this kinda cases we should use transient keyword before the property. Below program gives you more idea.
import java.io.Serializable;

public class Student implements Serializable{

	// when we serialize student object, the id will be zero (default value of the dataType)
	transient private int id;
	private String name;
	private int rollNum;
	
	
	// getters and setters goes here	
}


LindlarsForLife :)

0 comments:

Post a Comment