A Java Program to add two variable of user defined data type Distance. Everyone can suggest the improvement and extension to this program like implementation of method related to Subtraction of one distance from another, multiplication etc. There many other operation cab be performed on this Distance type like Declaring their Arrays etc.

/*
A Java Program to Demonstrate the concept of Class and Object by Defining a Class Distance which have two private variables feet and inch. Three public methods getDist(), showDist() and adDist() are also defined in it to acess the Private variables feet and inch. So the concept of Data Encapsulation and Hinding is implemented. This example also shows that capability of defining our own data types(in this case Distance). As far as scale unit feet and inch are concerned everybody know that 1 Foot = 12 Inches and in the method adDist() we have used it during addition of two Distance type variable d1 and d2.

*/

import java.util.*;//To use Scanner : a class which facilitate us to read input from Keyboard

class Distance
{


private int feet,inch; //Private data of type int


public void getDist() //Public method to read the Data(feet & inch) from KB

{
Scanner sc=new Scanner(System.in);

System.out.println("Feet : ");
feet=sc.nextInt();
System.out.println("Inch : ");
inch=sc.nextInt();

}

public void showDist() //Public method to show the Data(feet & inch) on Screen
{
System.out.println(feet + " Feet "+inch+" Inch " );
}

public Distance adDist(Distance d1, Distance d2)
//Public method of return type Distance with two Distance type parameters

{

Distance d3=new Distance();
d3.feet=d1.feet+d2.feet;
d3.inch=d1.inch+d2.inch;

if(d3.inch>=12)
{
d3.feet++;

d3.inch=d3.inch-12;
}
return d3;

}


}

class distest
{

public static void main(String args[])
{

Distance d1= new Distance();//Declaring three objects d1,d2 and d3 of type Distance
Distance d2= new Distance();
Distance d3= new Distance();
System.out.println("Enter the First Distance ");
d1.getDist(); //Calling get
System.out.println("Enter the Second Distance ");
d2.getDist();
d3=d3.adDist(d1,d2);
System.out.println("Result :");
d3.showDist();


}

}

Note : Adjust the comment sections according to your text editors or IDE.

0 comments:

Post a Comment

 
Top