Saturday 21 March 2015

Constructor && Method Overloading

CONSTRUCTOR  ::

Generally we can initiate the variables by two methods either 1) by using DOT operator or 2) by making a method and then call it.

But java or some other language supports a special method called constructor.
Constructor enables the objects to initiate itself when it is created..

For Example take a simple rectangle area calculation program

Class Rectangle
{
int length,breadth;
Rectangle(int x,int y )
{
length=x;
breadth=y;
}
int area( )
{
int a;
a=length * breadth; 
return(a );
System.out.println("Area of rectangle is:"+a );
}

Class calarea

{
public static void main( string args[])
{
Rectangle rect1= new Rectangle(10,15);
 rect1.area( );
}
}

In this program we initialise the object by using constructor Rectangle(int x,int y)..

Here this constructor is known as Parameterized Constructor that is because at the time of object intantiation,the constructor is explicitly invoked by passing certain arguments.
But if we want the constructor to automatically initialize the object variables with some default values at the same time of object intantiation ??? Then Default Constructors are used..

Use of default and parameterized constructor with example-

Class Rectangle
{
int length,breadth;
//Default Constructor 
Rectangle( )
{
length=0;
breadth=0;
}
//Parameterized Constructor
Rectangle(int x,int y )
{
length=x;
breadth=y;
}
int area( )
{
int a;
a=length * breadth; 
return(a );
System.out.println("Area of rectangle is:"+a );
}

Class calarea

{
public static void main( string args[])
{
Rectangle rect1= new Rectangle();
Rectangle rect2= new Rectangle(10,15);
rect1.area( );
 rect2.area( );
} }

Ans Will be....0 and 150


Properties of Constructor -


What can not?
1. "A constructor cannot be abstractstaticfinalnative, strictfp, or synchronized".
2. Interface cannot have constructor.
3. Constructor cannot return a value.{return object}


What can?
1. A constructor can be private.
2. Abstract class can have constructor.
3. A constructor can be overloaded.

4.Constructors have the same name as the class name.

Now Comes on the METHOD OVERLOADING

Method Overloading definition can be comprised with two points

1. Same method name
2. Different argument list 

Method Overloading is used when objects are required to perform the same task with different input parameter..We can understand method overloading more clearly bu refering the above example


Class Rectangle

{
int length,breadth;
//Default Constructor 
Rectangle( )
{
length=0;
breadth=0;
}
//Parameterized Constructor
Rectangle(int x,int y )
{
length=x;
breadth=y;
}
int area( )
{
int a;
a=length * breadth; 
return(a );
System.out.println("Area of rectangle is:"+a );
}

Class calarea

{
public static void main( string args[])
{
Rectangle rect1= new Rectangle();
Rectangle rect2= new Rectangle(10,15);
 rect1.area( );
rect2.area( );
}
 }

In this program we can see that same method "Reactangle" is using with two different parameter list so simply we can say that the constructor method is being overloaded...
First the method name will be matched after that it will match the number and type of the parameters and according to this call the function.

Overriding in java....

The Concept of overriding came when we drive a child class or derived class from the parent class or base class OR simply when the concept of inheritence uses...
When we define a method that has the same name,same argument,same return type as a method in the superclass and when that method is called,then method defined in the subclass is invoked and executed instead of the one in the superclass..That is Overriding..

Or in brief we can say that -
"If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java".

Lets see a simple example :

class Vehicle{  
 void run(){
System.out.println("Vehicle is running");
}  
}  
class Bike extends Vehicle{  
    
  public static void main(String args[]){  
  Bike obj = new Bike();  
  obj.run();  
  }  
}  

Output:Vehicle is running

The above program is without using the overriding concept.....Now we will see the same example to understand overriding concept --
In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.

class Vehicle{  
void run()
{
System.out.println("Vehicle is running");
}  
}  
class Bike2 extends Vehicle{  
void run(){
System.out.println("Bike is running safely");
}  
  
public static void main(String args[]){  
Bike2 obj = new Bike2();  
obj.run();  
}  

Output:Bike is running safely

Let take another example to understand overriding clearly..
Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.

class Bank{  
int getRateOfInterest(){
return 0;
}  
}  
  
class SBI extends Bank{  
int getRateOfInterest(){
return 8;
}  
}  
  
class ICICI extends Bank{  
int getRateOfInterest(){
return 7;
}  
}  
class AXIS extends Bank{  
int getRateOfInterest(){
return 9;
}  
}  
  
class Test2{  
public static void main(String args[]){  
SBI s=new SBI();  
ICICI i=new ICICI();  
AXIS a=new AXIS();  
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());  
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());  
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());  
}  
}  

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

in this example simply we have a class bank and his rate of intrest method  but many different-2 banks have different-2 rate of interest so they use the same method as defined in base class (Bank) and alter the behaviour of that method that is what Overriding..





Requirements  for Java Method Overriding :

  • method must have same name as in the parent class
  • method must have same parameter as in the parent class.
  • must be IS-A relationship (inheritance).


Now here's arise a question --Can we override a static method???

So the ans is "NO" we can't override a static method at all..Whereas it can be overload...

Point to be remember about static method and overriding :

Following are some important points for method overriding and static methods in Java :

1) For class (or static) methods, the method according to the type of reference is called, not according to the abject being referred, which means method call is decided at compile time.

2) For instance (or non-static) methods, the method is called according to the type of object being referred, not according to the type of reference, which means method calls is decided at run time..

/* Java program to show that if static method is redefined by
   a derived class, then it is not overriding. */

// Superclass
class Base {
     
    // Static method in base class which will be hidden in subclass 
    public static void display() {
        System.out.println("Static or class method from Base");
    }
     
     // Non-static method which will be overridden in derived class 
     public void print()  {
         System.out.println("Non-static or Instance method from Base");
    }
}
// Subclass
class Derived extends Base {
     
    // This method hides display() in Base 
    public static void display() {
         System.out.println("Static or class method from Derived");
    }
     
    // This method overrides print() in Base 
    public void print() {
         System.out.println("Non-static or Instance method from Derived");
   }
}
// Drived class
public class Test {
    public static void main(String args[ ])  {
       Base obj1 = new Derived();
        
       // As per overriding rules this should call to class Derive's static 
       // overridden method. Since static method can not be overridden, it 
       // calls Base's display() 
       obj1.display();  
        
       // Here overriding works and Derive's print() is called 
       obj1.print();     
    }
}

Output:

Static or class method from Base
Non-static or Instance method from Derived

Here the point to be understand is "Base obj1 = new Derived()" exactly then simply it means hat it means "Reference of base class but object of derived class"..

In case of static method -- method invoked with base class will be called as in point  (1).
In case of instance or non static method -- method invoked with derived class will be called as in point (2).

3) An instance method cannot override a static method, and a static method cannot hide an instance method. For example, the following program has two compiler errors.

/* Java program to show that if static methods are redefined by
   a derived class, then it is not overriding but hidding. */

// Superclass

class Base {

     
    // Static method in base class which will be hidden in subclass 

    public static void display() {

        System.out.println("Static or class method from Base");
    }
     
     // Non-static method which will be overridden in derived class

     public void print()  {
         System.out.println("Non-static or Instance method from Base");
    }
}

// Subclass

class Derived extends Base {

     
    // Static is removed here (Causes Compiler Error) 

    public void display() {

        System.out.println("Non-static method from Derived");
    }
     
    // Static is added here (Causes Compiler Error) 

    public static void print() {

        System.out.println("Static method from Derived");
   }

4) In a subclass (or Derived Class), we can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods — they are new methods, unique to the subclass.