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

Comments

Post a Comment

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Program to input age from user and throw user-defined exception if entered age is negative

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.