Sunday, September 21, 2014

# 18 - OBJECT CONSTRUCTION

Hello,

We all know that Java is an Object Oriented Programming. Meaning, Java works with objects. In this post, we are going to discuss about construction of Java objects. Yes, objects can be constructed using Constructors of a Java class. Constructors will make sure that all the variables / members of current class and its super class are initialized properly.

Constructor
Constructors are the code that runs whenever we use new keyword. A constructor is more like a normal method in a Java class but with special rules for a special purpose.
Here are the basic ground rules one should follow while working with Constructors in a Java class.
  1. Constructor name MUST match the name of the class.
  2. Constructor MUST NOT have a return type.
  3. Constructor can have ANY access modifier. To know more about access modifier read this.
  4. If we don’t define any constructor in a Java class, the compiler will automatically provide us a default constructor. Default constructor will always be NO ARGUMENT constructor.
  5. Constructors can be OVERLOADED. If we define either no-argument or overloaded constructor, then the compiler will NOT provide any default constructor.
  6. Constructors can NEVER be OVER-RIDDEN.
  7. The first statement of any constructor MUST be this or super. If we don’t write it, compiler will insert the first statement for us.
  8. We can invoke a constructor ONLY in 2 ways.
i.   While creating an object
ii.  From another constructor


Let us see in detail about the constructor and its special rules. A basic constructor is as follows,
public class ConstructorDemo 
{
	public static void main(String... strings)
	{
		// create an object of ConstructorDemo class
		ConstructorDemo cDemo = new ConstructorDemo();	// O.K.
		
		// below code doesnt compile.
		ConstructorDemo cDemo1 = new ConstructorDemo(1,2); // ERROR.!	
	}
}
A normal java class appear as shown above. Observe that I didn't define any constructor in the ConstructorDemo class and I am trying to create an object using no argument constructor and also using a constructor which takes 2 integers.

Creating an object with no argument constructor is O.K. coz, if we didn't define any constructor in the class the compiler will provide a default no argument constructor. It looks like,
//default constructor
public ConstructorDemo()
{
	super();
}
We can see that the constructor provided by compiler,
  1. doesn't have any arguments.
  2. doesn't have a return type.
  3. has same name as Class name.
  4. gets the same access modifier as the class. Read Java Access Modifiers to know more about modifiers.
  5. No code will be provided inside the compiler provided constructor except super() method call. This super() invokes the parent class no-argument constructor. In our case, ContructorDemo is not extending any class. So by default every class extends Object class. Hence the super() method invokes NO ARGUMENT constructor of Object class.
But when I try to create an object with overloaded constructor, I get a compile time error saying,

The constructor ConstructorDemo(int, int) is undefined

It is correct. We haven’t defined a constructor which takes 2 integers. Compiler will ONLY provide us NO ARGUMENT constructor. For overloaded constructors, we have to define ourselves or else we get a compile time error.

Now see this below code,
public class ConstructorDemo 
{
	// overloaded constructor
	public ConstructorDemo(int a, int b)
	{
		// if we don’t write super(), compiler will add for us
		super();
		
		// set a and b values to instance variables
	}
	
	
	public static void main(String... strings)
	{
		// create an object of ConstructorDemo class
		ConstructorDemo cDemo = new ConstructorDemo();	// ERROR.!
		
		// below code doesnt compile.
		ConstructorDemo cDemo1 = new ConstructorDemo(1,2);	// O.K.
	}
}
You can see that I have defined an over-loaded constructor which takes 2 integers. When I try to compile this class, I get an error at line 16 saying,

The constructor ConstructorDemo() is undefined

Why is it so? Ideally if we don’t define any constructor, compiler provides no-argument constructor. BUT if we define any constructor in the class, then the compiler WON’T provide us any constructor. In the above example, I have defined an overloaded constructor. So compiler will not provide no-argument constructor. Hence we get compile time error saying constructor is undefined.

this & super

this and super are keywords in Java, so we cannot use them as variables. The purpose of both the keywords is same. Only difference is,

this    – always refers to the current class object
super – always referes to the super class object (parent)

These 2 keywords are also used for calling the constructors.

this()    – calls other constructor in the same class.
super() – calls the constructor in the super (parent) class.

Both the methods this() and super() can be overloaded to call the overloaded constructors.

One rule you should burn in your head is, constructor calling should be the very first statement in the constructors. We canNOT use both this() and super() in a constructor.
If we invoke super() method, then we canNOT use this() in that constructor. If we invoke this() in the first statement, then we canNOT use super() in that constructor.

See the below code for better understanding.
public class ConstructorDemo {

	// no-arg constructor
	public ConstructorDemo()
	{
		super(); // invokes the super class no-arg constructor
		
		System.out.println("In NO argument constructor.");
	}
	
	// overloaded constructor
	public ConstructorDemo(int a)
	{
		// should be the very first statement
		this(); // invokes no-arg constructor of current class
		
		System.out.println("In 1 argument constructor.");
	}
	
	// overloaded constructor
	public ConstructorDemo(String str , int a)
	{
		// should be the very first statement
		this(a); // invokes one integer argument constructor of current class
		
		System.out.println("In 2 argument constructor.");
	}
	
	public static void main(String... strings)
	{
		// create an object of ConstructorDemo class
		System.out.println("Create object using No argument Constructor.");
		ConstructorDemo cDemo = new ConstructorDemo();
		System.out.println();
		
		System.out.println("Create object using 1 argument Constructor.");
		ConstructorDemo cDemo1 = new ConstructorDemo(10);
		System.out.println();
		
		System.out.println("Create object using 2 argument Constructor.");
		ConstructorDemo cDemo2 = new ConstructorDemo("Number", 20);
		
	}
}
The above program is self-explanatory. I have defined 3 constructors, no-argument constructor and 2 overloaded constructor.
Line 37 invokes one integer argument type constructor which again invokes no–argument constructor type and it invokes super class no-argument constructor.

Line 41 invokes 2 argument type constructor which invokes one integer argument constructor which again invokes no–argument constructor type which again invokes super class no-argument constructor.

That’s how the chain goes. A call to this() just means we are delaying the call to super class constructor. At the end of the chain, some constructor must make the call to super class constructor..!

When I compile and run the above program, I get the below output,
Create object using No argument Constructor.
In NO argument constructor.

Create object using 1 argument Constructor.
In NO argument constructor.
In 1 argument constructor.

Create object using 2 argument Constructor.
In NO argument constructor.
In 1 argument constructor.
In 2 argument constructor.
We have seen how an overloaded constructor can be called using this(). Now lets us how an overloaded super class constructor can be called.
public class ConstructorDemo extends SuperClass
{
	// constructor
	public ConstructorDemo()
	{
		System.out.println("Child class - no argument constructor");
	}
	
	public static void main(String... strings)
	{
		// create an object of ConstructorDemo class
		System.out.println("Create object using No argument Constructor.");
		ConstructorDemo cDemo = new ConstructorDemo();
	}
}

class SuperClass
{
	// constructor
	public SuperClass()
	{
		System.out.println("Super class - no argument constructor");
	}
}
See the above program,

ConstructorDemo extends SuperClass
SuperClass extends Object

When I compile and ran the program, I get the below output,
Create object using No argument Constructor.
Super class - no argument constructor
Child class - no argument constructor
Observe that I haven’t placed any super() statement in ConstructorDemo constructor. But still the control has gone to SuperClass default method. Coz the compiler has places super() statement for us.

Things get much more interesting when the super class doesn't have a default constructor.
public class ConstructorDemo extends SuperClass
{
	// constructor
	public ConstructorDemo(int a, int b)
	{
		//super();		-- ERROR.! SuperClass doesn't have no-argument constructor
		super(a, b);	// O.K.
		System.out.println("Child class - 2 argument constructor");
	}
	
	public static void main(String... strings)
	{
		// create an object of ConstructorDemo class
		System.out.println("Create object using 2 argument Constructor.");
		ConstructorDemo cDemo = new ConstructorDemo(10, 20);
	}
}

class SuperClass
{
	int a;
	int b;
	
	// constructor
	public SuperClass(int i1, int i2)
	{
		super(); // no-argument constructor of Object class
		System.out.println("Super class - 2 argument constructor");
	}
}
In the above program, in SuperClass you can see that I haven’t defined any no-argument constructor.
As I have defined a 2 argument constructor in the super class, compiler will NOT provide us a no-argument constructor.

Hence we have to explicitly call the super constructors from the child class constructors using the super().
See the 2 argument constructor of ConstructorDemo class. I tried calling the super constructor using super() with no arguments and I get an error saying,

The constructor SuperClass() is  undefined

It is correct, coz we have defined 2 argument constructor in the super class, hence we need to explicitly call it from the child class.
Below is the output I get when I try to compile and run the above program.
Create object using 2 argument Constructor.
Super class - 2 argument constructor
Child class - 2 argument constructor
Here comes the very BIG question.

Q) - Why super class constructor gets called when we try to create an object of the child class?

A) Because the call to the super class constructor will ensure that when a constructor is invoked, it can rely on all the fields / instance members in its superclass being initialised.

When we create an object of a class, using that object we are free to use parent class members. To make the parent class variables available to the child class object, the super() call will make sure that super class variables are initialised and are ready to use by the child class object.

That is the reason super class constructor call is mandatory at the time of object creation.

Thanks :)

Sunday, August 31, 2014

# 17 - LOAD it OVER to OVERLOAD

Hello,

We have already discussed about Overriding concept in my previous post. Now let us see how Overloading concept works and the benefits that we get in using it. Before proceeding further and for better understand I suggest you to refresh the overriding concept in my previous post.

Overloading – This word can be divided into OVER and LOAD. Yes, we are gonna load a method overly.
But the question comes, how to load a method, right?  I believe you guys knew it, just by adding arguments to a method.



OVER-LOADED Methods

We already know that overriding concept uses 2 excellent features of Java – Inheritance and Polymorphism. If you are not aware of this, please read this before you proceed further. These 2 features are mandatory to implement the Overriding concept.

But for overloading concept, only Polymorphism feature is mandatory. Inheritance feature is optional. It allows us to reuse the same method name with different arguments and optionally different return types.
public class AddDemo
{ 

 // addition of 2 integers
 public void add(int a , int b)
 {
  System.out.println("Add 2 Integers --> "+(a+b));
 }
 
 // addition of 2 decimals -- OVER-LOADED METHOD
 public void add(double a, double b)
 {
  System.out.println("Add 2 Decimals --> "+(a+b));
 }
 
 // addition of 3 decimals -- OVER-LOADED METHOD
 public void add(int a, int b, int c)
 {
  System.out.println("Add 3 Integers --> "+(a+b+c));
 }
 
 // addition of integer and decimal and returns a decimal -- OVER-LOADED METHOD
 public double add(int a, double b)
 {
  System.out.println("Add Integr and Decimal and returns a decimal --> "+(a+b));
  
  return a+b;
 }
 
 // <--- This method will throw error --->
 // Error : Duplicate method add(int, int) in type AddDemo
 public int add(int a , int b)
 {
  System.out.println("Add 2 Integers and returns an Integer --> "+(a+b));
  
  return a+b;
 }
 
 
 // main method - entry point of a program
 public static void main(String... args)
 {
  AddDemo aD = new AddDemo();
  
  // declare & define variables
  int a = 10;
  int b = 20;
  int c = 30;
  double d = 1.5;
  double e = 1.75;
  
  // invoke the methods
  aD.add(a, b);
  aD.add(a, b, c);
  aD.add(d, e);
  double f = aD.add(a, e);
  System.out.println("AddDemo.main().. F value --> "+f);
 }
}
Above program is self-explanatory. I have method add() which takes 2 integer primitives. And I need some more methods in the same class which need to do addition. So I tried using the same method name but with different arguments.

But you may be wondering how Java compiler will get to know which add() should be invoked when all the methods in the class have same name. The compiler will recognize the correct method by the number and type of arguments that we pass while calling the method.

The point you need observe in the above program is the method add(int a , int b) which returns an integer. That method gives a compile time error saying “Duplicate method in the class”. Why so?

'Coz overloading is possible ONLY in below combinations,
  1. Change the number of arguments
  2. Change the type of arguments
  3. Change the number of arguments and their types.

Changing the return type of a method and not the type of arguments is not allowed in the same class. Coz the compiler will not be able to recognize a method by the return type.
  
Below methods are not allowed in the same class,
public void add(int a, int b) { }
public int add(int a, int b){ }
Beginners get confused easily to find a method if it has been overridden or overloaded in a subclass. Try to recognize if a method is overridden or overloaded in the below program.
//class AddDemo
public class AddDemo
{ 
 // add method
 public void add(int a, int b){ }
 
 // subtract method
 public void subtract(int a, int b){ }
 
}

class Demo extends AddDemo
{
 
 // Overridden or Overloaded method ??
 public void add(int a, double b){ }
}
add() in class Demo is overridden or overloaded ?

It is overloaded. Coz overridden method should have same number and type of arguments. If you create an object to the Demo class, it is capable to invoke add() which is in its class and also add() in AddDemo class (parent class).

The overloading concept becomes much more interesting when we use the Objects instead of primitives. See the below program.
public class TestAnimal{
 
 public void eat(Animal an)
 {
  System.out.println("Animal method invoked ::");
 }
 
 // Overloaded method
 public void eat(Horse an)
 {
  System.out.println("Horse method invoked ::");
 }
 
 public static void main(String... args)
 {
  TestAnimal testObj = new TestAnimal();
  Animal animalObj = new Animal();
  Horse horseObj  = new Horse();
  
  // invoke the methods 
  testObj.eat(animalObj);
  testObj.eat(horseObj);
 }
}

//class Animal
class Animal 
{ 
 
}

// class Horse - subclass of Animal
class Horse extends Animal
{
 
}
In the above program, it is obvious that the output will be,

Animal method invoked ::
Horse method invoked ::
But what if we use an Animal reference to a Horse object? See below statement,
Animal animalRefToHorse = new Horse();
testObj.eat(animalRefToHorse);
which eat method will be invoked? 
The method that takes Animal object or Horse object?

To understand better, let us go back to Overriding concept. In Overriding, at compile time the Java compiler assumes it as Animal Object and at runtime it realizes that the object is of Horse type and hence it invokes the method in the Horse class. That’s how the Runtime or Dynamic Polymorphism works.

But in overloading concept, even if the compiler realizes the object at runtime is of Horse type, it still consider as Animal object coz its reference is of type Animal. Hence the above statement will invoke the eat() method that takes Animal object and we get the output as,

Animal method invoked ::

Confused ??!! :D

To summarize the entire explanation, here are the straight 2 points that you should remember,
  1. Reference type decides which overloaded method need to be invoked.
  2. Object type decides which overridden method need to be invoked.

I have summarized the differences between Overriding and Overloading in the below table.


Overloaded Method
Overridden Method
Arguments(s)
Must change
Must NOT change
Return Type
Can change
Must NOT change. Can return sublcass Object
Exceptions
Can Change
Reduce or eliminate. Must not throw broader or new exceptions
Access
Can change
Must not be more restrictive. Can be same / less
Invocation
Based on Reference Type
Based on Object Type



Thanks :)

Tuesday, June 10, 2014

# 16 - RIDE it OVER to OVERRIDE

Hello,

Many of us have heard about Overriding and Overloading concepts in Java. I still get confused whenever I face this question in interviews..:P So I thought of clearing mine and your confusion about them in the coming posts by disussing about these topics in detail.! :D

This post is all about Overriding and in the next post we will see Overloading and their difference. There are many differences between each other but still the beginner’s gets confused in understanding these concepts. So I thought of trying my part to make it easy in understanding..:P

The overloading and overriding concepts apply only to methods. Whenever you hear people using these words, you can be sure that there are planning to do something with methods.

Just to repeat, this post is completely dedicated to readers. (I know it is
a bad joke..:P)
This post is completely dedicated to Overriding..!

Overriding –This word can also be divided into OVER and RIDE. Yes. We are gonna go for a ride on the methods..!





OVER-RIDDEN Methods

The overriding concept is related to 2 excellent features in Java – Inheritance and Polymorphism
Had there been no inheritance concept, there wouldn’t have been overriding concept. So burn this in your head that overriding can happen only when Inheritance is there. And regarding Polymorphism, we will see about in few seconds.
//class Animal
public class Animal { 

 public void eat(){
  System.out.println("Animals eat grass");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // OVERRIDDEN method 'coz eat() already exists in Animal (parent) class
 public void eat(){
  System.out.println("Horses eat grass and oats");
  // add Horse related code
 }
}
In the above program, you can see that we use the extends which says that there is a Inheritance concept and the parent class has a method eat() which says "all animals eat grass". But I have a subclass Horse which is also an animal but eats grass and oats as well. In this case, I want to define my own specifications for Horse. That’s where the overriding concept comes into the picture. So I have overridden the existing eat() method to the subclass Horse and implemented in my own way. Simple..!

Then here comes other excellent feature of Java – Polymorphism.
Poly – many
Morph – forms.
In other words, an object appearing in different forms is called Polymorphism. Let’s see what it has to do with overriding.
public class TestAnimal{
 public static void main(String... x){
  Animal a = new Animal();
  Horse h  = new Horse();
  
  a.eat(); // prints animal eat()
  h.eat(); // prints horse eat()
  
  //polymorphism comes here
  Animal an = new Horse();
  an.eat(); // which eat method will invoke ?
  
  // this statement gives compile error
  //Horse hr = new Animal();
  
 }
}

//class Animal
class Animal { 

 public void eat(){
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // OVERRIDDEN method 'coz eat() already exists in Animal (parent) class
 public void eat(){
  System.out.println("Horse.eat()");
  // add Horse related code
 }
 
 public void run(){
  System.out.println("Horse.run()");
 } 
}
I know this will be a confusing one but I try my best to make it simple and easy. So to sum up the above program, I have created 2 objects,
Animal a = new Animal();
Horse h  = new Horse();
Using Animal object I can invoke 1 method ie., a.eat()
Using Horse object I can invoke 2 methods ie., h.eat() and h.run()

Now the interesting part comes here,
Animal an = new Horse();
How many methods can I call using "an" ?

Well, first analyze the above statement. new Horse() means object of Horse class and the reference is Animal. So we are assigning the horse object to an Animal reference. It is legal coz Horse is a subclass of Animal class.
As we have assigned it to an Animal reference, the compiler assumes that it is an animal object. The Animal has only one method – eat(). So if we try to invoke run() method using “an”, you get a compiler saying “The method run is undefined for the type Animal”.

Now if I call an.eat() method, which eat method will be invoked ? As the compiler assumes that "an" is an animal object hence it calls animal eat() method ??

The answer is NO.

The Horse eat() method will be invoked and hence we get the output as,

Horse.eat()

Let me explain why it happens. Just now I said that the compiler assumes "an" object as Animal object. But at runtime, it will realize that it is a Horse object which is assigned to Animal reference. Hence it will call Horse eat() method. Compiler assuming at compile time and realizing the actual object at runtime is called Dynamic Binding or Runtime Polymorphism.

Here are the rules with Overriding.
  • The argument list MUST exactly match the overridden method.
//class Animal
class Animal { 

 public void eat(String food){
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // OVERRIDDEN method 'coz eat(food) already exists in Animal (parent) class
 public void eat(String food){
  System.out.println("Horse.eat(food)");
  // add Horse related code
 }
 
 // This is NOT overridden method coz arguments doesn't match
 // This is just like any other method in a class.
 public void eat(String food, String water){
  System.out.println("Horse.eat(food, water)");
 } 
}
  • The return type must be same or subtype of the return type declared in the parent class.
//class Animal
class Animal { 

 public void eat(String food){
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // This method gives copile time error saying "The return type is incompatible with Animal.eat(String)"
 // coz the return types are different 
 public int eat(String food){
  int i = 3;
  System.out.println("Horse.eat(food)");
  return i;
 } 
}
  • The access level cannot be more restrictive but can be same or less restrictive than the overridden method.
//class Animal
class Animal { 
 
 // this method is with public access
 public void eat(String food){
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // This method throws the compile time error saying "Cannot reduce the visibility of the inherited method from Animal"
 // The overriding method canNOT reduce its visibility (public to private is reducing its visibility)
 private void eat(String food){
  System.out.println("Horse.eat(food)");
  // add Horse related code
 } 
}
  • The overriding method must NOT throw checked exceptions that are broader than those declared by the overridden method but it can throw narrower exceptions.
    • A method that declares a FileNotFoundException cannot be overridden by a method that declares SQLException, Exception or any other checked exception unless it is a subclass of FileNotFoundException.
//class Animal
class Animal { 
 
 // this method is with public access
 public void eat(String food) throws FileNotFoundException{
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // This method throws the compile time error saying "Exception Exception is not compatible with throws clause in Animal.eat(String)"
 // The overriding method canNOT throw broader exceptions than those declared in the overridden method.
 // This method can throw FileNotFoundException or its subclass exceptions.
 // It is completely legal if this method doesn't throw any Exception
 public void eat(String food) throws Exception{
  System.out.println("Horse.eat(food)");
  // add Horse related code
 } 
}
  • We canNOT override final and static methods. 
//class Animal
class Animal { 
 
 // this method marked final, so canNOT override
 public final void eat(String food){
  System.out.println("Animal.eat()");
 }
 
 // this method marked static, so canNOT override
 public static void run(){
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // trying to override final eat(food), 
 //we get compile time error saying "Cannot override the final method from Animal"
 public void eat(String food){
  System.out.println("Horse.eat(food)");
  // add Horse related code
 }
 
 // trying to override static run(), 
 //we get compile time error saying "This instance method cannot override the static method from Animal"
 public void run(){
  System.out.println("Horse.run()");
 }
}


That's all with the Overriding concept. The Overloading concept is much easier to explain and to understand. Till then enjoy a ride with Overridden methods.!

Thanks :)

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 :)

Monday, May 19, 2014

# 14 - All About Java Modifiers (Part III)

Hello,

We have seen all about Java Access Modifiers and so it’s time to know all about Java Non-Access Modifiers.

Just to make it clear,

Java Access Modifiers – are the modifiers which provide the facility to access/restrict the class members from a different class.
Java Non-access Modifiers – are the modifiers which are not used for accessing/restricting the class members. In short, all the modifiers which are not related to visibility/accessing the class members are Non-access Modifiers.

Each non-access modifier works in its own way which is completely different from other modifiers. Here are the non-access modifiers that are available in Java.
  • final
  • abstract
  • synchronized
  • native
  • strictfp
  • static
  • transient

All the above words are reserved, meaning they are keywords in Java. Let us look into each modifier in detail.

final :
The final modifier can be applied to classes/methods/ variables. It will act differently when applied to a class from the way it acts when applied to a method/variable.
As the name suggests, when final keyword is used it restricts the user to modify the class/method/variable details. JVM will decide it as FINAL, it doesn't listen to anyone else..!

final modifier when applied to a class
So when I apply the final keyword to a class, that class canNOT be extended by any other subclass. See the below example
// ClassA
public final class ClassA{
 public static void main(String... s){
  System.out.println("ClassA.main()");
  }
 }

// ClassB
class ClassB extends ClassA{
 // class members and variables goes here 
}
You can see that I have a class ClassA which is marked as final and I tried to extend the ClassA so that I can use ClassA variables and methods. But as ClassA is a final class, if I try to extend ClassA I get a compiler error saying,
The type ClassB cannot subclass the final class ClassA
If we want to restrict other developers in extending our class features, mark it as final. By marking it final we can be sure that no other developer can modify the features of our class.

final modifier when applied to a method
When a final keyword is used in a method’s signature, then that method canNOT  be overridden in any subclass. Imagine I have a method in a class which finds two strings are meaningfully equal are not. I want other developers to use this method without modifying the logic inside the method. That’s where I use final keyword to the method which informs other developers that the logic inside the method shouldn’t be changed.
public class ClassA{
 public final void methodA(){
  System.out.println("ClassA.methodA()");
 }
}

class ClassB extends ClassA{ // we can extend ClassA as it is not marked as final
 public void methodA(){ // Compiler error..!!! method is marked as final in classA, so we cannot use method in its subclass.
 }
}
If we try to compile the above program, we get the below error.
Cannot override the final method from ClassA
Make sure you use the final keyword for methods with great caution. If there are any bugs in the logic of your method, then the developers who use your method may start searching for you..:P
final modifier when applied to variable
When a final modifier is used to a variable, then that variable value cannot be changed in its corresponding scope. In other words, the memory address associated with that variable cannot be changed. If we try to do so, we will get a compiler error.
public class ClassA{
 
 final int classInt = 50; 
 
 public void methodA(){
  final int methodInt = 100;
 }
}
You can see that I have 2 final variables. One is of class scope and the other is of method scope. The class variable classInt value cannot be modified in the entire class and the method variable methodInt cannot be modified in the method method.

abstract:
The abstract modifier can be used only with classes and methods but not with variables. The word abstract means that something not described clearly or not having clear idea/picture. The same meaning applies in Java as well.

abstract modifier when applied to a class:
If a class contains at least one abstract method, then the class should be marked as abstract. It is illegal to have even a single abstract method in a class that is not explicitly declared abstract. But we can have an abstract class with no abstract methods.
I have no intention to confuse you. See the below code :)
public abstract class ClassA{
 
 // concrete method
 public void methodA(){
  
  // your code and logic for this method goes here. 
 }
 
 // concrete method
 public void getUserDeatails(){
  // connect to the database and get the user details.
 }
}
In the above Java class, we don’t have any abstract methods. But still, it is legal to declare the class a abstract.
public class ClassA{
 
 // concrete method
 public void methodA(){
  // your code and logic for this method goes here. 
 }
 
 // abstract method - no implementation code
 public abstract void getUserDeatails();
}
In this Java class, you can see that we have one abstract method and one concrete method. But the class is not declared as abstract. When we try to compile this class, we get a compiler error saying,
The type ClassA must be an abstract class to define abstract methods
So the bottom line is, if a class contains at least 1 abstract class then we are forced to declare the entire class as abstract.

abstract modifier when applied to a method:
An abstract method is a method that has been declared but not implemented. A method which is marked as abstract will never have implementation code. The implementation for the abstract methods will be developed in the concrete class that implements the abstract class.
Let’s take an example for better understanding.
Imagine I have a class Car and different companies want to implement their own design of the car. So I have written an abstract method design() in the class Car so that the car that implements the class Car can implement their own design() code depending on their own car configuration. Audi wants to implement the design() differently and BMW might want to implement differently. That’s how the abstract class/methods are useful by providing the capability to implement the code specifically..!
Here are the clues to differentiate between abstract method and concrete methods,
  1. abstract methods are marked as abstract. The concrete methods are not marked as abstract.
  2. abstract methods doesn’t include curly braces or it will not have a method body. The abstract method ends with semi-colon. The concrete methods contain open/close curly braces and don’t end with semi-colon.
  3. The concrete methods provide actual implementation code where as abstract method does not.
public abstract class Car{
 
 // abstract method
 public abstract void design();
 
 //concrete method
 public void move(){
  // the logic in this method can be shared by all the sub classes
  System.out.println("Car.move()");
 }
}

// sub class
class BMW extends Car{
 
 public void design(){
  // Implement their own BMW Design of the car
 }
}

// sub class
class Audi extends Car{
 
 public void design(){
  // Implement their own Audi Design of the car
 }
}
synchronized
The synchronized keyword is associated with Threading concept.  When multiple threads try to access one single resource, thread 1 may not see the change thread 2 made which causes logical errors in the program. This can be prevented by using the keyword synchronized. This keyword can be applied ONLY to methods and cannot be used for classes or variables.
We can see more about this modifier during the concept of Multi-Threading in Java :)

native
native modifier can be used ONLY with method not with class nor variables. By using this modifier we are letting know the JVM that the code inside the method is not Java. Earlier (may be before Java 1.5v) developers use other languages for increasing the performance but later Java has undergone many changes in the performance sections and hence native modifier has become less used.
All you just need to know about native modifier is it allow us to use other programming languages.

strictfp
strictfp is a keyword used with ONLY methods. strictfp says “I strictly follow IEEE754 Floating Point standards”. If we declare a method with strictfp, then the code inside the method will follow IEEE 754 standards. Now don’t ask me what is IEEE 754, if you really wanna know you can see it here.

There are chances that different platforms (32 bit, 64 bit etc.,) may produce different results of calculation if decimals are involved (may be coz of truncating). To make sure our code follows a particular standard for calculating the decimal results on any platform so that we get the same results, we better use strictfp keyword.

We will discuss about the other 2 modifiers (static and transient) in next post..!! Thanks :)