Saturday, 7 December 2013

Super Keyword in Java


Use of super keyword comes in java when inheritance is implemented i.e. when we have super class and sub classes as explained in the topic Inheritance in Java.
Usage are as explained below:
1.      To call a super class method :
Normal method call:
When we want to call a method of super class in a sub class, it can be done by using super.mathodname(). It is demonstrated in below example:

Parent and child class
reference of subclass calling sub class method
output


Overridden method call:
When the overriding method needs to call the overridden method of the parent class, it can be called using super.sameMethodName().
It is demonstrated in below example:
Consider the super class from above example.Subclass has overridden the super class method and in the overridden method, it has called the same method of super class using super.

sub class overriding super class method method()

output

2.      To explicitly call the super class constructor(both default and paramaterized) : Though it is not needed because the super class constructor is implicitly called from the sub class constructor.  
      
      Default constructor is called in below manner :


      Note : while calling constructor of base class from sub class constructor, the super() must be the first statement.

      Similarly paramarized constructor can be called.



3.      To access non private super class members : All non private members in parent class can be accessed using super keyword as shown in below example :


Inheritance in Java


 Inheritance in simple language means to have something in common in child with parent. Inheritance in java also has the same concept like a child inherit some characteristics and surname from parent. It is one of the basic OOP concepts used in java along with Encapsulation, Polymorphism and Abstraction.

            Inheritance is a way to define IS-A relationship between classes. Inheritance is used when we have to design a new class and this new class needs some code which another class already has. In implementing this, the fields and the methods can be reused without writing them again.

        In Java, inheritance is achieved through extends and impelements keywords. By using these keywords properties of one object can be acquired in another object. The class from which n new class is derived is known as subclass and the class from which subclass is derived is called superclass.

For example:
Consider the Animal as a base class and Cat as the derived class from it and follow the code written below:


Base Class : Animal

Child class : Cat

Main Class
The output for this program would be :

                                          Legs :4
                                          sounds as meow

Diagrammatically, inheritance is represented as below:

Inheritance is represented using an arrow
Types Of Inheritance:
There are three types of inheritance in java.
1. Single
2. Multilevel
3. Hierarchical

As shown in below diagram:

Types of Inheritance in Java



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());
}
}


.

Monday, 30 September 2013

Access Specifiers/Modifier types in Java


Access specifiers in java are provided to achieve one of the OOP concept of Encapsulation.
Use of access specifiers helps in data hiding and making the system less prone to issues of accidental changes in data.
Access  specifiers in java are defined for Classes, methods and variables.there are four types of access specifiers available:

1.       Public
2.       Protected
3.       Default(no specifier)
4.       Private

1.    Public :
This access specifier is the most open one.
The variables, methods,  constructors, classes or interffaces defined as public can be accessed from anywhere in Java world.
Note :
a.    While accessing public class in other package, it needs to be imported first.
b.   The derrived classes autmatically get access to public members of the base class.

Example :
The main() method defined in java to be called to start any application is made public so that java interpreter can access it.

Variable declaration:
Public  Integer iAccess;

Method declaration:
Public  void method()
{
        System.out.println(“ example for protected ”);
}


2.    Protected:
This access specifier is a super set of “Default” access with access in package and to all subclassess of the base class in which the protected variable/method is declared.
Note:
a.    Protected is applicable only to variables, constructors and methods, cannot be used for class/interface.
b.   The protected variables can be accessed in derrived class only directly, cannot be called with the reference  of the base class.
For example : a variable protected integer a can be accessed in the other package derrived class  System.out.println(a)  - legal
Base base = new base();
Base.a  -- illegal
   
Example:
Variable declaration:
Protected String sAccess = “Access Specifier”;

Method declaration:
Integer add(int a, int b)
{
                return((Integer)(a+b));
}



3.    Default (No Specifier) :
When no specifier is assigned to any method, constructor,  class or variable, it is considered to be as default. The method/variable can be accessed from any class in the same package. It is also called as “package level” access. 

Example :
Variable declaration :
String sAccess = “Access Specifier”;

Method declaration:
Integer add(int a, int b)
{
                return((Integer)(a+b));
}


4.    Private :
Private access specifier is to scope a variable, constructor or method to the particular class in which it is declared/defined. It is the most restricted access level. It is the main way of obtatining encasulation in java.
Note:
a.    Classess/Interfaces cannot be declared private.
b.   Priavte variables can be accesed from outside class through public getter methods present in the class.

Example:
Variable declaration :
Private String sAccess = “Access Specifier”;

Method declaration :
Private Integer add(int a, int b)
{
                return((Integer)(a+b));
}


Above concepts can be put in table as below
  
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
default Y Y N N
private Y N N N

Friday, 23 August 2013

Polymorphism - Method Overloading and Method Overriding

Polymorphism


Polymorphism, in Greek means “many forms”. It simply refers to the different behavior of same thing in different ways according to the situations based on type of inputs. It simply works on the fundamental of message passing.

Consider the real time example of a Fund transfer:
Consider fund transfer as the common functionality used. Now based on the option selected for payment type the payment will be done i.e. the type of transaction as RTGS or NEFT can be selected by us and the transfer will take place based on that input. Thus you can see how same functionality behaved differently based on the types of mode.

Secondly, consider our sight as one function. If we see a lion coming towards us, we will run while if it’s a rabbit, we will go towards it. Here seeing is a function which is behaving in different manner based on the type of animal we are seeing.

Polymorphism in JAVA is one of the OOP concepts along with inheritance, encapsulation and abstraction. It helps in making the code more flexible and reusable for future enhancements.
It is achieved in two ways:
Static Polymorphism (method overloading)
      Dynamic Polymorphism (method overriding)

1.      Static Polymorphism :
This is termed as overloading /compile time binding. Here the compiler decides which method would be called based on the type/number of parameters getting passed while calling the method. The binding happens at compile time.
Overloaded methods are methods which have different signature. Method signature includes name, number of arguments, and type of arguments and order of arguments to that method.
So the overloaded methods

a.       Have the same name.
b.      Have different parameter list.(number of parameters/type of parameters/order of parameters)
c.       May appear in same class or subclass.

For example: see the below code snippets to understand different ways for overloading a method.

types of overloading methods
  
Constructor overloading is one of the application of static polymorphism in which a class can have multiple constructor with same name varying in list of arguments getting passed to it. It is as shown in below code.

Constructor Overriding



2.      Dynamic Polymorphism:
This is termed as overriding or run-time binding. In this type of polymorphism, the calling method is decided at run time based on the type of object calling the method. The overridden methods have the same name and same signature.  Overriding helps in achieving flexibility and extensibility as the new functionality can be introduced with minimal changes in the code.

Overriding methods:

a.      Can not appear in same class. They need to be defined in sub class.
b.     The accessibility of the overridden method cannot be reduced i.e. for example public method cannot be made private/default/protected in sub class.
c.      The private or static or final methods cannot be overridden.
d.      Signature and name must be exactly same.
e.      Overriding method cannot throw a checked exception which is higher in hierarchy than what is thrown by the overridden method. For example: If overridden method has thrown an IOException then the overriding method cannot throw java.lang.Exception.
         
       This will be clear with the below code:
       The base class is Shape which has one method defined as Area() which will be overridden in the sub            classes Circle and Rectangle. 

Base Class


Circle sub class extending Shape class. Area() method is oerridden



Rectangle sub class extending Shape class and overriding Area() method.

Main class calling different methods with different objects

     The result for above class execution is as below. It is clear that the methods are getting called based on the type of object which is getting created.


Sunday, 18 August 2013

Simplifying Encapsulation

Encapsulation

                Encapsulation in very simple terms means data/information hiding. Encapsulation is a process or mechanism which binds the data and methods together and keeps them safe from outside interference, misuse and access. It is about not allowing arbitrary access to the code written in one module from other modules. The access to these codes is provided through a well defined interface.

Let’s take a real world example to understand the concept.

In a vehicle, there are several parts being used in the engine like shaft, valves, piston, heater etc. But if we see, we are not affecting any of these components and their functionality.We are given just one interface to use them is to start the engine. In this way the internal details are kept unaffected from external impact and similarly the engine parts are not affecting anything outside.

                Coming to Java, the encapsulation is achieved by a class. A class is a blue print for a real time entity defining its structure and behavior. The data defined in a class are known as member variables/instance variables and the code which operates/manipulates the data are known as member methods.

Below image explains the use of encapsulation:

Encapsulation explained in pictorial view 



                   Private methods/private variables are accessed only by the same class. Public variables/methods are exposed to outside world to access the private data.

                  To hide the complexity, methods and variables are declared with the access specifiers. Typically variable are declared as private and the methods as public.

Private: accessible within the class.

Public: accessible from anywhere.

Default: accessible within the package.

Protected: accessible from all the sub classes within same/different packages.


A sample class code would look like as below:

A sample class code


Here the private member variable cannot be accessed from outside this class, so public getter and setter methods are declared to access from outside only through these methods.

Saturday, 17 August 2013

Abstraction simplified

Abstraction


Abstraction is an essential element of object oriented programming. Abstraction is used to manage the complexity of an implementation. Through Abstraction, relevant details are shown and irrelevant details are hidden.
For example, A car is driven by a person without knowing its internal architecture and construction. Here the relevant work for a person is to drive so other details like that of engine is not needed to be provided to him and thus abstraction comes into the picture.
The abstraction can be achieved by hierarchical classification of a complex system.
For example, If we take the example of a Car as a single object. It consists of several sub systems such as Seat, Brakes, Steering, Engine etc. and similarly these subsystems are again made up of more specialized parts.

Abstraction implementation in Java

In Java, Abstraction is achieved by declaring the methods without any implementation in interface or class and then defining these methods in the derived classes. This simply means that the actual definition of what a method will do is left for implementation on the class which can define the method according to the need. Abstraction is used when we know that something has to be there but not sure how exactly it should look like.
there are two ways to implement and attain the abstraction.
1. Abstract Class
2. Interface

1. Abstract Class : 

                             An Abstract class is a class of which no instance is created. To use an abstract class, it needs to be extended and the derived class must not have any abstract method. Abstract methods are declared in the abstract class which does not contain any method body. To use this method, it needs to be overridden in the sub class extending this abstract class.

For example :
When we have to create a class Shape, we know that each shape must have the method called area() but it may have different implementation for different types of shapes
skeleton for Abstract class is as explained below :
one abstract class Shape is created with two abstract methods area() and perimeter().

Abstract class Shape 








The Circle and Rectangle class extends this abstract class and they need to implement the abstract methods of Shape class. A shown below, both methods are implemented as per the type of shape. Her we can see that every shape needs to have its area and perimeter, thus these are defined in the abstract class and then implemented in the derived class and every subclass of this base class will have to implement these methods.

Derived class Circle

Derived class Rectangle

2. Interface: 

                   It is another way to implement Abstraction in java. Interfaces are just like classes with its all member variables defined as public, final and static i.e. no instance variables and all methods as abstract and public. It is denoted with keyword interface. The classes can implement any number of interfaces and any number of classes can implement same interface. the implementing class must define all the methods declared in the interface. Interfaces are created when we know that what a class must do but not how to do.
Like Abstract class, interface van not have any concrete method in it.
An interface abstraction is implemented like as below:
Shape is one interface and Circle and Rectangle are two classes which implement this interface.

Interface definition

Circle class implements Shape interface


Rectangle class implements Shape



.






















































When to Use Interface and When to use Abstract Class

  1. When we know that one functionality should be same across all the sub classes, Abstract class is to be used. For example : Every vehicle must have a method called start() which should be their in every vehicle derived     and its implementation must be same.
  2. When we use Interface, there is always a possibility that we can implement more than 1 interfaces thus multiple inheritance can be used.