Home Java Beginners Constructor Overloading in Java
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Constructor Overloading in Java

Advertisement
An example that shows the use of constructor in Java programming.

Constructor Overloading in Java

     

Here, you will learn more about Constructor and how constructors are overloaded in Java. This section provides you a brief introduction about the Constructor that are overloaded in the given program with complete code absolutely in running state i.e. provided for best illustration about the constructor overloading in Java.

Constructors are used to assign initial values to instance variables of the class. A default constructor with no arguments will be called automatically by the Java Virtual Machine (JVM). Constructor is always called by new operator. Constructor are declared just like as we declare methods, except that the constructor don't have any return type. Constructor can be overloaded provided they should have different arguments because JVM differentiates constructors on the basis of arguments passed in the constructor.

Whenever we assign the name of the method same as  class name. Remember this method should not have any return type. This is called as constructor overloading. 

We have made one program on a constructor overloading, after going through it the concept of constructor overloading will get more clear. In the example below we have made three overloaded constructors each having different arguments  types so that the JVM can differentiates between the various constructors.

The code of the program is given below:

public class ConstructorOverloading{
  public static void main(String args[]){
  Rectangle rectangle1=new Rectangle(2,4);
  int areaInFirstConstructor=rectangle1.first();
  System.out.println(" The area of a rectangle in 
  first constructor is :  " 
+ areaInFirstConstructor);
  Rectangle rectangle2=new Rectangle(5);
  int areaInSecondConstructor=rectangle2.second();
  System.out.println(" The area of a rectangle in 
   first constructor is :  " 
+ areaInSecondConstructor);
  Rectangle rectangle3=new Rectangle(2.0f);
  float areaInThirdConstructor=rectangle3.third();
  System.out.println(" The area of a rectangle in first 
  constructor is :  " 
+ areaInThirdConstructor);
  Rectangle rectangle4=new Rectangle(3.0f,2.0f);
  float areaInFourthConstructor=rectangle4.fourth();
  System.out.println(" The area of a rectangle in first 
  constructor is :  " 
+ areaInFourthConstructor);
  }
}

class Rectangle{
  int l, b;
  float p, q;
  public Rectangle(int x, int y){
  l = x;
  b = y;
  }
  public int first(){ 
  return(l * b);
  }
  public Rectangle(int x){
  l = x;
  b = x;
  }
  public int second(){
  return(l * b);
  }
  public Rectangle(float x){
  p = x;
  q = x;
  }
  public float third(){
  return(p * q);
  }
  public Rectangle(float x, float y){
  p = x;
  q = y;
  }
  public float fourth(){
  return(p * q);
  }
}

Output of the program is given below:

C:\java>java ConstructorOverloading
The area of a rectangle in first constructor is : 8
The area of a rectangle in first constructor is : 25
The area of a rectangle in first constructor is : 4.0
The area of a rectangle in first constructor is : 6.0

Download this program

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 22, 2005

Related Tutorials

Ask Questions?    Discuss: Constructor Overloading in Java   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Alfonce king
April 16, 2011
ticket system

For more than 20 years, Country Express has delivered services for all rail operations- transit, light rail, high speed rail and long haul train journey in the country. Efficiency is a daily challenge that operators of rail transportations systems face. From operation management to passenger management, operators are entrusted with the responsibility of ensuring high levels of efficiency and safety at all times. The company had recently restructured itâ??s ticketing scheme and has entrusted your group to develop a system for them embodying the following modules; 1. Registration Module Every customer has the option to register onto the system. This information is used for the reward module mentioned below. Customer details such as name and identity card are required for registration. The system will subsequently generate a unique 6 digit code which will be used by the customer to purchase train tickets. This is a one-time registration. The customer however, need not register to purchase a train ticket, in which case points will not be credited to the user for purchases of the train ticket. 2. Reward Module For every RM1.00 spent, a customer shall accumulate one point which will be credited to the account of the customerâ??s 6 digit code. 3. Ticketing Module Provides a facility to the customer to purchase ticket at the train station. There are a total of 30 stations. The cost of getting from one station to an immediate station is RM1.00. Using the same calculation, the ticket price of getting from station 1 to 6 is RM5.00. In the same way, ticket price for getting from station 10 to 30 should be RM20.00. The rates however differ at night (7 pm â?? 11 pm) and early mornings (6 am â?? 7:15 am) where a 25% discount shall apply. Children are subjected to a 50% discount regardless of the time of travel. For group purchase (more than 5 people), a 10% discount shall apply. For every 1000 points accumulated by a customer, a discount of RM5.00 shall apply. Fields required for purchasing ticket(s) â?? 6 digit code (optional), station (departure), station (arrival), travel time (24 hours), No of adults, No. of children. The system will subsequently generate the ticket price and the customer will enter the payment amount. A remainder is produced should the payment amount exceed the required amount. Apart from generating a ticket the system will also display a customerâ??s cumulative points on each generated ticket. Develop a stand alone application using Java which will observe the defined specifications. In the interface use appropriate GUI components. Make appropriate use of the Layout managers. The interface should be attractive, very user friendly, crash proof, intuitive (i.e. acts as someone would expect it to act), and reasonably realistic. Java Programming Page 1 of 3 Diploma Part 2 Asia Pacific Institute of Information Technology 2009 * You can use your own judgements and assumptions should the above requirement specification is insufficient in order to develop a realistic program. You are required to include all the assumptions that you made in your assignment.
neo
May 28, 2011
java

This is very good site
Md.Danish Ahmad
June 24, 2011
Constructor

Sir,Plzz explain about constructor
Nikitha Nahar
September 12, 2011
Incorrect print statements.

In the constructor overloading program the print statements are incorrect . They should be correspondingly for first , second , third and fourth constructor. Good program.
jitendra
September 23, 2011
java

public class ConstructorOverloading{ public static void main(String args[]){ Rectangle rectangle1=new Rectangle(2,4); int areaInFirstConstructor=rectangle1.first(); System.out.println(" The area of a rectangle in first constructor is : " + areaInFirstConstructor); Rectangle rectangle2=new Rectangle(5); int areaInSecondConstructor=rectangle2.second(); System.out.println(" The area of a rectangle in first constructor is : " + areaInSecondConstructor); Rectangle rectangle3=new Rectangle(2.0f); float areaInThirdConstructor=rectangle3.third(); System.out.println(" The area of a rectangle in first constructor is : " + areaInThirdConstructor); Rectangle rectangle4=new Rectangle(3.0f,2.0f); float areaInFourthConstructor=rectangle4.fourth(); System.out.println(" The area of a rectangle in first constructor is : " + areaInFourthConstructor); } } class Rectangle{ int l, b; float p, q; public Rectangle(int x, int y){ l = x; b = y; } public int first(){ return(l * b); } public Rectangle(int x){ l = x; b = x; } public int second(){ return(l * b); } public Rectangle(float x){ p = x; q = x; } public float third(){ return(p * q); } public Rectangle(float x, float y){ p = x; q = y; } public float fourth(){ return(p * q); } }
anjali
October 19, 2011
java programming

Write a program using overload constructor to calculate the area of square (length*length) and display it. Display I and II. I. Initialize the sides of the square=3. II. User will enter the sides ofthe square. how to solve it!
margub Khan
October 24, 2011
constructor overloading

nice example is this and i think it is one of the best
Arun
December 19, 2011
I want all definition from java

Send me the link java's definition.
Nikhil Patel
December 26, 2011
JAVA

hello sir, my question is how to write JAVA APPLET code in NetBeans7 ?
janani6*
January 7, 2012
java

how to understand java programs?
NEERAJ KUMAE NAGER
January 18, 2013
constructor

difference b/w overloading and overriding
Balkrishna
February 15, 2012
java

i m not understand ur example please a good ex. are given
Sudhansh Srivastava
February 17, 2012
regarding the upper program.

how do we can minimise this constructor overloading program, and also tell me that how a user can be asked to give input to the program.
venky
March 25, 2012
java

constructors metarials
mandal Reddy. Veena Reddy
April 10, 2012
gud

Good one
Mohd Arshad
May 28, 2012
java

what is polymorphim?
rajesh
July 7, 2012
wow

current solution for constructor overloading in java
m.saravanakumar
July 13, 2012
java

hi sir,how can i learn java with in short time of period..thnk u sir
sunil kumar
July 30, 2012
JAVA SE &EE

LEARN EVERYTHING, nice concept of constructor , thanks.....
lee
August 13, 2012
thnx

thankd
NIRAV
August 27, 2012
Program output

IN this program 14 error is there
A Sreepriya
October 1, 2012
Hai

Its very good example and easy to understand by the person who is very new to java
poonam singh
October 11, 2012
nice

vry hlpful in my proct.......
dileep
July 1, 2013
query

what is meant by constructor overloading ?explain eith an example
dileep
July 1, 2013
query

what is meant by constructor overloading ?explain eith an example
DMCA.com