OO设计-有理数类的设计
完整的有理数类的代码
package oo;
public class RationalNumber {
private int numerator;//分子
private int denominator;//分母
public int GetNumerator() {
return numerator;
}
public int GetDenominator() {
return denominator;
}
private static int gcd(int x,int y) {
if(x%y==0)
return y;
else
return gcd(y, x%y);
}
public RationalNumber (int numerator,int denominator) {
int gcd=gcd(numerator, denominator);
this.numerator=((denominator>0)?1:-1)*numerator/gcd;
this.denominator=Math.abs(denominator)/gcd;
}
public RationalNumber add(RationalNumber newRational) {
int x=this.numerator*newRational.GetDenominator()+this.denominator*newRational.GetNumerator();
int y=this.denominator*newRational.GetDenominator();
return new RationalNumber(x,y);
} //加
public RationalNumber subtract(RationalNumber newRational) {
int x=this.numerator*newRational.GetDenominator()-this.denominator*newRational.GetNumerator();
int y=this.denominator*newRational.GetDenominator();
return new RationalNumber(x,y);
} //减
public RationalNumber multiply(RationalNumber newRational) {
int x=this.numerator*newRational.GetNumerator();
int y=this.denominator*newRational.GetDenominator();
return new RationalNumber(x,y);
} //乘
public RationalNumber divide(RationalNumber newRational) {
int x=this.numerator*newRational.GetDenominator();
int y=this.denominator*newRational.GetNumerator();
return new RationalNumber(x,y);
} //除
}
测试代码
package oo;
public class Main {
public static void main(String[] args) {
RationalNumber x=new RationalNumber(4,2);
RationalNumber y=new RationalNumber(1,7);
System.out.println("x="+x.toString());
System.out.println("y="+y.toString());
System.out.println("x+y="+x.add(y));
System.out.println("x-y="+x.subtract(y));
System.out.println("x*y="+x.multiply(y));
System.out.println("x/y="+x.divide(y));
}
}
尝试描述怎么与c语言的有理数代码相比较,为什么你设计的类更加面向对象?
Java中设计的类更面向对象的原因是类提供了一种模板,可以根据相应的要求更简洁方便的创造更改对象。
讨论
1.别人如何复用你的代码?
导入自己编写的有理数包,从而调用类中的属性和方法
2.别人的代码是否依赖你的有理数类的内部属性?当你的有理数类的属性修改时,是否会影响他人调用你有理数类的代码?
不依赖,不会
3.有理数类的public方法是否设置合适?为什么有的方法设置为private?
合适,提高代码的安全性。