有理数类设计

1.有理数类的代码

package Rl;

public class Rational{

      private int Rl_numerator;//分子
      private int Rl_denominator;//分母

      public Rational (int numerator,int denominator)//构造函数
      {
          this.Rl_numerator = numerator;
          this.Rl_denominator = denominator;
      }
     

      public int getNumerator()//获取分子
      {
          return this.Rl_numerator;
      }

      public int getDenominator()//获取分母
      {
          return this.Rl_denominator;
      }

      public Rational add(Rational first,Rational second)//加法
      {
          int n = first.Rl_numerator * second.Rl_denominator + second.Rl_numerator * first.Rl_denominator;
          int d = first.Rl_denominator * second.Rl_denominator;
          return new Rational(n,d);
      }

      public Rational subtract(Rational first,Rational second)//减法
      {
          int n = first.Rl_numerator * second.Rl_denominator - second.Rl_numerator * first.Rl_denominator;
          int d = first.Rl_denominator * second.Rl_denominator;
          return new Rational(n,d);
      }

      public Rational multiply(Rational first,Rational second)//乘法
      {
          int n = first.Rl_numerator * second.Rl_numerator;
          int d = first.Rl_denominator * second.Rl_denominator;
          return new Rational(n,d);
      }

      public Rational divide(Rational first,Rational second)//除法
      {
          int n = first.Rl_numerator * second.Rl_denominator;
          int d = first.Rl_denominator * second.Rl_numerator;
          return new Rational(n,d);
      }

      public boolean equal(Rational first,Rational second) //判断是否相等
      {
          if ((first.Rl_numerator == second.Rl_numerator)&(first.Rl_denominator == second.Rl_denominator)) {
              return true;
          } else {
              return false;
          }
      }

      public int intValue()//返回整数
      {
          return this.Rl_numerator / this.Rl_denominator;
      }

      public double doubleValue()//返回浮点数
      {
          return 1.0 * this.Rl_numerator / this.Rl_denominator;
      }

      public String toString()//返回字符串
      {
          return this.Rl_numerator + "/" + this.Rl_denominator;
      }
  }

2.与有理数类不同包的其他类中调用有理数类的测试代码

  import Rl.*;

  public class App {
      public static void main(String[] args) throws Exception 
      {
          Rational a = new Rational(1, 2);
          System.out.println(a.toString());
      }
  }

4.别人如何复用你的代码

导入有理数类的包

5.别人的代码是否依赖你的有理数类的属性?当你的有理数类的属性修改时,是否会影响他人调用你有理数类的代码?

依赖,会影响

6.有理数类的public方法是否设置合适?为什么有的方法设置为private?

public类设置的方法有获取私有属性和返回不同类型私有数据和加减乘除以及判断相等与否,都是在操作中需要用到的相关基础操作,private类设置的有两个私有数据,因为从外面不需要知道里面具体结构,所以隐藏

posted @ 2020-09-29 21:26  月光寰宇(白靖)  阅读(229)  评论(0编辑  收藏  举报