0% found this document useful (0 votes)
3 views2 pages

Types of Constructors in Java

Java constructors

Uploaded by

TRANAND TR
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Types of Constructors in Java

Java constructors

Uploaded by

TRANAND TR
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Ex.

3 – Program to distinguish the different types of constructors

Aim
To distinguish the different types of constructors

Algorithm
Step 1: Define a class named Conversion.
Step 2: Declare two instance variables: iKm of type int to represent
kilometers and dMile of type double to represent miles.
Step 3: Define a no-argument constructor Conversion() within the class and
initialize iKm to 100.
Step 4: Define a one-argument constructor Conversion(int) within the class
and initialize iKm with the provided argument.
Step 5: Define a method miles() within the class to calculate and print the
equivalent miles for the value of iKm using the conversion factor (1 km =
0.621371 miles).
Step 6: In the main() method, create three objects: obj1 with no
arguments, obj2 with 500 as the argument, and obj3 using obj2 to initialize
it.
Step 7: Call the miles() method using two different objects.
Source Code

class Conversion
{
public int iKm;
public double dMile;

public Conversion() //no argument constructor


{
iKm=100;
}
public Conversion(int k) //one-argument constructor
{
iKm=k;
}
public Conversion(Conversion cObj) //one-argument constructor
{
iKm=[Link];
}

public void miles()


{
dMile = iKm*0.621371;
[Link](iKm+ "km equal to " + dMile + " miles");
}

public static void main(String[] args)


{
Conversion obj1 = new Conversion();
Conversion obj2 = new Conversion(500);
Conversion obj3 = new Converison(obj2);

[Link]();
[Link]();
[Link]();
}
}

You might also like