Polymorphism 101

Posted on March 14th, 2005 by marjorie.
Categories: very old stuff.

Reference:

Rational

Posted on March 14th, 2005 by marjorie.
Categories: very old stuff.

// Rational Class
public class Rational {

private int a; // numerator
private int b; // denominator

// Class Constructor
// creates rational objects without passing any arguments.
// The default Rational number is 0/1. a=0 and b=1
Rational (){
a = 0;
b = 1;
} // end of default constructor

// Constructor with arguments
Rational (int a1, int b1){
a = a1;
if (b1 == 0){
// denominator is zero not acceptable
// create the rational number as a default
// number.
a = 0;
b = 1;
}else{
// denominator is not zero assign b1 to b
b = b1;
}
} // end of constructor with arguments

//Inspectors
//acts on an object and simply return the value for the data members
public int get_a(){
return a;
}
public int get_b(){
return b;
}

// A method whose name is toString takes no arguments,
// returns a String object that represents the content
// of the Rational number. Example: let r=1/2. The method
// returns a string ” 1/2″ that represents the contents of
// the Rational number r.

public String toString(){

return ” ” + get_a()+ “/” +get_b();
}
}

************************************************************************
public class TestRational {
public static void main (String[] args){

// declaration of the rationa objects
// initialization of the Rational Objects
// r1 = 0/1
Rational r1 = new Rational(5,0); // calling the default constructor
// r2 = 0/1
Rational r2 = new Rational(1,2); // calling the default constructor
// r3 = 0/1
Rational r3 = new Rational(2,3); // calling the default constructor

System.out.println(”Rational Number r1 = ” + r1.toString());
System.out.println(”Rational Number r2 = ” + r2.toString());
System.out.println(”Rational Number r3 = ” + r3.toString());
}//end main
}// end TestRational