Pages

Thursday, 18 July 2013

CONSTRUCTOR


Definition - Constructor is a special type of method i e. used to initialize a newly created object & is just called after memory is allocated for object.

Rules to be followed while defining constructor
  1. It has same name as that of class.
  2. No return type should be there.
  3. Constructors can use any access modifier, including private.
Note:-  You can define method with the same name as of class. Example-

class A{
  private A()
{
// Constructor with private access modifier, it means object of class A can only be instantiated with //in the class not outside it.To instantiate from outside class you have to use static method with in // //class A.
}
public void A()
{
// Legal method
}

public static void main(String... x)
{
new A(); // anonymous object
}
}

Q1. Do constructors have  return type?
Ans. Yes. Constructors return reference of their class.
         Do some practical .

 class A{
  A( ){

return ; // will not give any error. This proves that constructors returns something.
}
public static void main( )
{
System.out.println(new A( ));  // It will print A@1270b73 (ClassName@hashcode)  constroctur
}
}


OOP's says there are 2 types of constructors -


  1. Default Constructor  2. Parameterized  Constructor

1. Default Constructor - The constructor that is provided by the compiler implicitly.


eg.
 class A
{
 gear = 1;
    cadence = 10; 
    speed = 0; 
public static void main(String... x)
   {
    new A( ); 
   }
}
The program will be compiled and executed even constructor is not defined.Compiler first look into class for your defined constructor if it is not defined,then it defines it.
If no user defined constructor is provided for a class, compiler initializes member variables to its default values.
 class Bicycle
{
 int speed ;
String riderName ;
public void display()
{
System.out.println("Rider's Name -"+riderName+" Speed -"+speed);
}
public static void main(String... x)
   {
    Bicycle b=new Bicycle( );
  b.display();
   }
}

Output -  Rider's Name -null Speed -0

Conclusion -

  1. numeric data types are set to 0
  2. char data types are set to null character(‘’)
  3. reference variables are set to null


2. Parameterized Constructor -  Constructors that have parameters & follows the below given points.
  1. Constructor Can Take Value , Value is Called as – “Argument“.
  2. Argument can be of any type i.e Integer,Character,Array or any Object.
  3. Constructor can take any number of Argument.
  4. See following example – How Parameterized Constructor Works ? -
public double computePayment(double loanAmt,double rate,double futureValue,int numPeriod) {
    double interest = rate / 100.0;
    double partial1 = Math.pow((1 + interest), 
                    - numPeriods);
    double denominator = (1 - partial1) / interest;
    double answer = (-loanAmt / denominator)
                    - ((futureValue * partial1) / denominator);
    return answer;
}
 computePayment(32500.62,8.56,42500.33,5)    // Arguments are passed here


Note: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.

C++: - introduced concept of copy constructor ie. Parameterized Constructor in Java.
 If copy constructor was concept of OOP's then every technology( inc. Java,.Net, PHP etc)            would implemented it.Copy Constructor means you are creating copy of object at time of              creation of object.Therefore the concept was not taken as granted.

CONSTRUCTOR CHAINING

Definition-  Calling one constructor from another.

class A
{
A()
{
this(7);
}
A(int i)
{
this(i,6.5);
}
A(int x, float y)
}
public static void main(String... x)
   {
  new A();
   }
}

Why this keyword is used?
this reference ID of newly created object. It doesn't create new object.

Why Java didn't use Class Name instead of this keyword say A(7) instead of  this(7)?
There may be some method with the name of class eg. void A(int j){}.JVM will get confused that which code is to be run.

Scenario:-  It tells us the utility of constructor chaining,

Client asked you to write a program where database connection should be created or provide five resources of connection at time of creation of object.Five process to be carried out as follows -
  1. Create Database
  2. Do File Input Output Process
  3. Create GUI.
  4. Create Connection to network
Generally we try to put code for all above process in one constructor which leads to complexity & difficulty while debugging.Therefore, do categorization,i e. provide separate constructor to each resource via constructor chaining.

class Client{

Client()
{
// default constructor
}
  Client(String db)
{
// create file object to carry out i/o operations File file=new File("path to file");
Client(file);
}
Client(File file)
{
//carry out i/o operation 
Client(component); // component can be any Frame/JFrame, Panel/JPanel
}
Client(Component component)
{
// Design your GUI
Client(String IPAddress,String portNo); // call the constructor to eastablish connection with network

}
Client(String IPAddress,String portNo)
{
// Connect to remote IP
}
public static void main(String... x )
{
new Client( );
}
}








No comments:

Post a Comment

 

Blogger news

Blogroll

Most Reading

Tags