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

Java Ex 3

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)
1 views2 pages

Java Ex 3

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
You are on page 1/ 2

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=cObj.iKm;
}

public void miles()


{
dMile = iKm*0.621371;
System.out.println(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);

obj1.miles();
obj2.miles();
obj3.miles();
}
}

You might also like