Home » Codes » Rational number class in Java

Rational number class in Java

Apr 17, 2012 by     3    Placed under: Codes, Java, OOP
1
SHARES

Rational number class in Java

This tutorial is about making Rational number class in Java.I hope this tutorial is helpful.

class Rational{ // Rational Number Class
private int nem;
private int dem;
public Rational(){
nem=0;
dem=0;
}
public Rational(int n , int d){ // Parameterized constructor
nem=n;
dem=d;
}
public void setnem( int a){ // setter
nem=a;
}
public void setdem( int a){
dem=a;
}
public int getnem(){ // getter
return nem;
}
public int getdem(){
return dem;
}
public void add (Rational r){ // add function
nem=nem+r.nem;
dem=dem+r.dem;
}
public void sub (Rational r){ // sub function
nem=nem-r.nem;
dem=dem-r.dem;
}
public void mul(Rational r){
nem=nem*r.nem;
dem=dem*r.dem ;
}
public void div(Rational r){
nem=nem*r.dem;
dem=dem ;
}
}

class Test2{ // Test2 class for Main
public static void main(String o[]){
Rational r=new Rational(25,30); // Test data
Rational r1=new Rational(20,40);
r.add(r1);
System.out.println(r.getnem());
System.out.println(r.getdem());
r.sub(r1);
System.out.println(r.getnem());
System.out.println(r.getdem());
r.mul(r1);
System.out.println(r.getnem());
System.out.println(r.getdem());
r.mul(r1);
System.out.println(r.getnem());
System.out.println(r.getdem());
}
}
Loading Disqus Comments ...
Loading Facebook Comments ...

Subscribe to our Newsletter