Friday, 25 November 2016

Define a class Fraction having data members numerator and denominator. Initialize three objects using different constructors and display its fractional value.

In this program, we have declared a class Fraction having three parameterized constructors one takes two parameters int and double other takes both parameters as int, etc. in that we initialized data members. After that we have created an object of Fraction class in main( ) by passing different values in constructor call and called display( ) method.


PROGRAM
public class Fraction {

 double numerator,denominator;
 
 Fraction (int a, double b) {
  
  numerator=a;
  denominator=b;
 }
 
 Fraction (int x, int y) {
  
  numerator=x;
  denominator=y;
 }
 
 Fraction(double m, double n) {
  
  numerator=m;
  denominator=n;
 }
 
 void display() {
  double fraction=numerator/denominator;
  System.out.println ("Fraction = "+fraction);
 }
 public static void main(String[] args) {
  
  Fraction f1 = new Fraction(12,12.3);
  f1.display();
  
  Fraction f2 = new Fraction(10,12);
  f2.display();
  
  Fraction f3 = new Fraction(10.5,13.5);
  f3.display();
 }
}
OUTPUT
C:\>javac Fraction.java
C:\>java Fraction
Fraction = 0.975609756097561
Fraction = 0.8333333333333334
Fraction = 0.7777777777777778

1 comment: