Home » Codes » Rational number class in Java

Rational number class in Java

Apr 17, 2012 by     3 Comments    Placed under: Codes, Java, OOP
pinit fg en rect gray 28 Rational number class in Java
java 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());
}
}

Written by Rizwan Khan

pp av Rational number class in Java

0saves


If you enjoyed this Article, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
+0 -0




Related Articles:

Loading Disqus Comments ...
Loading Facebook Comments ...

Subscribe to our Newsletter

To subscribe to our newsletter simply add your email below. A confirmation email will be sent to you!