Saturday, 5 October 2013

final keyword in Java


           Final keyword in java has different usage based on the context in which it is used.
Final keyword can be used for variables, class or methods with giving different meaning to them respectively. 
It is used for below types in java.
a.   Class
b.   Methods
c.   Variables

Class:
A class declared with final keyword cannot be derived. Implicitly all the methods defined in a final class are final. Many classes in java library are declared as final. One of the very known example is java.lang.String class.
Note:
a.   An Abstract class cannot be declared final.
b. Using private and final both at the same time for a class makes the final redundant as the private class itself cannot be accessed by its sub classes.

Syntax:
Public final class Sample
{
}

Example:
Public final class FinalClass{}  -- declaring a class as final
Public class DerrivedClass extends FinalClass{} – this is not allowed.

Methods:
                A final method cannot be overridden or hidden by sub classes. This functionality is used where we need to take care that a subclass should not alter the behavior of a method to maintain consistency of the class.
Note:
An Abstract method cannot be declared final.

Syntax:
Public final void method()
{
                System.out.println(“in final method”);
}

Example:
Public class Sample
{
                Public final void method();
}

Public class DerrivedSample extends Sample
{
                Public voif method() --- This is not possible.
}

Variables:
                A variable declared final can bee initialized only once. It may be initialized value at the time of declaration or by assignment. A final variable which is not initialized at time of declaration is called “blank final” variable.

Note:
a. The blank final variable needs to be initialized in constructor else it results in compile time error and similarly, final blank static variable needs to be initialized in static initialization.
b. When a reference is made final, that means that this reference cannot be made point to any other object but the object to which it is pointing can be modified if that is a mutable class object.

Syntax:

public final int PI = 3.14;

Friday, 4 October 2013

Static keyword in java

Static keyword in java can be used for following three scenarios:

1.       Class variables
2.       Methods
3.       Block of code

Static data members:
Static data members (variables) are the variables which are to be used at class level. These are defined in a class outside any method, block or constructors with the keyword “static”. These are common to the entire class and only one copy will be available irrespective of how many objects will be created. Static variables will be stored in static memory. These are created when the program starts and destroyed when the program stops.

Syntax:
Public static String str1;
Or
Static public String str1;

They can be accessed as beow:
ClassName.variableName;

Methods:
Just like static variable, static method is a method which is common to the entire class. Static methods are called directly using class name. These cannot be accessed using any object reference. Static methods cannot access any non static member of the class while other methods/blocks can use static methods.

Syntax:
Public static Integer getTotal()

They can be accessed as below:
ClassName.methodName();

Static Blocks:
The static block is a block of code inside a class which will be executed when a class is first loaded. Static block is used to initialize the static members of the class just as constructor helps in initializing the instance members.

Syntax:
Class Sample
{
                Static
{
// code to be written
}
}

Important point:
When to use static and when not:
Statics are used when data is not instance dependent and same state is needed for the static data for all instances to be created. Static should be used only when they are actually required reason being, as they create dependencies and references to other classes and class loaders in JVM and they stay in memory for longer time. They won’t be considered for garbage collection when they are done with current work as they have to be de-referenced with their loading classes.


Example for static variables, static method and static block:

package test;
public class StaticSample
{
            //declaring static variable to have count of objects
private static int count = 0;  
            //constructor to increase count
public StaticSample()
            {
                        count++;
            }
           
//static block which will be called at first time class is loaded
static  
            {
                        System.out.println("in static block");
            }

            //static method
public static void printCount()
            {
                        System.out.println(" Count value : " +count);
            }          
           
}

//Main class to see how static works.
package test;
public class MainClass
{
public static void main(String[] args)
            {
                        static Sample sam1 = new StaticSample();
                        static Sample.printCount();
                        static Sample sam2 = new StaticSample();
                        static Sample.printCount();
            }

}

The result for above program would be as below:
in static block
Count value : 1
Count value : 2

Wednesday, 2 October 2013

Classes and Objects


Class :
          Class is the blue print of the real objects to be created. The class gives the skeleton for an entity to be created for real time processing. Class is a software template that defines the methods and variables to be included in a particular kind of Object.
A class may contain member variables, methods, constructors and static blocks which can be used to define and manupulate state and behavious of an object.

Object :
           The java is all about objects. An Object is the real entity in the world. Every object will have its state and behavior. Concept of Object can be easily understood taking any really time entity around us say Dog, television, Fridge or car etc.  A car may have states like number of wheels, type of engine etc and behvior like way of start, speedup etc.

Below is the syntax for the class.

Access specifier Class ClassName
{
                Member variables --- defines state of an object
                Methods --- defines the behaviour of the object
}

Object declaration will be like below:

ClassName object = new ClassName()

Example:
        We can define a class Vehicle to have an skeleton for all types of vehicles by preparing set of properties and type of processes required to use those vehicle. After that we can create real time object such as car, truck or tempo depending upon the states(properties).

Declaring a class : Vehicle
public class Vehicle
{
            //member variables which will define the state of a vehicle
private int wheels;
            private String sengineType;

            //setter method to set number of wheels
public void setWheels(int wheels)
{
                this.wheels = wheels;
}

//getter method to retrieve the number of wheels
public int getWheels()
{
                return this.wheels;
}             
}

See below, how will we use this class to instantiate any real object.
public class Demo
{
            //main method
            Public static void main(String args[])
{
            //calling default constructor to create an object.
Vehicle car = new Vehicle();       
Vehicle tempo = new Vehicle();

//calling setter method to set the states of the car object
            car.setWheels(4);
            tempo.setWheels(3);

            //calling getter method to access the object states
            System.out.println(“ Car : No. of wheels :”+car.getWheels());
System.out.println(“ Tempo : No. of wheels :”+tempo.getWheels());
}
}


.