面向对象练习

来源:互联网 发布:淘宝一颗钻在哪看 编辑:程序博客网 时间:2024/06/05 08:16

/*
 * 练习一:
 * 1.建立一个图形接口,声明一个面积函数。圆形和矩形都实现这个接口,并得出两个图形的面积。
 * 注:体现面向对象特征,对数值进行判断。用异常处理。不合法的数值要出现“这个数值是非法的”提示,不再进行运算。
*/
class NoValueException extends RuntimeException{
 NoValueException()
 {
  super();
 }
 NoValueException(String message)
 {
  super(message);
 }
}
interface Areaable{
 double getArea();
}
class Rec implements Areaable{//矩形
 private int length,width;
 public Rec(int length,int width)
 {
  if(length<0 || width<0)
  {
   throw new NoValueException("这个数值是非法的");
  }
  this.length=length;
  this.width=width;
 }
 public double getArea()
 {
  return length*width;
 }
}
class Circle implements Areaable //圆形
{
 private int radius;
 private static final double PI=3.14;
 public Circle(int radius)
 {
  if(radius<=0)
  {
   throw new NoValueException("这个数值是非法的");
  }
  this.radius=radius;
 }
 public double getArea()
 {
  return PI*radius*radius;
 }
}


/*
描述Person
  属性:姓名,年龄
  行为:1.说出姓名和年龄。2.判断是否是同一个人(同姓名,同年龄视为同一人)
  提示:判断姓名相同的方法到API文档String类中查找。
*/
class Person
{
 private String name;
 private int age;
 Person(String name,int age)
 {
  this.name=name;
  this.age=age;
 }
 public void speak()
 {
  System.out.println(this.name+"..."+this.age);
 }
 /**
  既然要判断对象是否相同,直接使用object类中的方法
  但是还是要依据子类的特征来判断,直接覆盖Object中的方法equals。
  */
 public boolean equals(Object obj)//这是Person类中的方法
 {
  if(!(obj instanceof Person))
  {
   throw new ClassCastException("类型错误");
  }
  //判断姓名和年龄是否相同,这些都是Person的属性,所以必须向下转型
  Person p = (Person)obj;
  return this.age==p.age && this.name.equals(p.name);
                           //!!!name是String类型的,而String本身是一个类,name就相当于是String类
                           //的对象。这个equals方法是String类中的方法!
 }
}
//主函数测试一下
//public class Demo2
//{
// public static void main(String[] agrs)
// {
//  Person p1 =new Person("lala",12);
//  Person p2 =new Person("lala",12);
//  boolean x=p1.equals(p2);
//  System.out.println(x);
// }
//}

/*多态练习
*/
class A{
 void fun1()
 {
  System.out.println(fun2());//this.fun2()是默认的,是本类A的
 }                              //继承,多态。本类型引用指向子类型对象
 int fun2()
 {
  return 123;
 }
}
class B extends A{
// void fun1()
// {
//  System.out.println(fun2());//this.fun2()。B类继承了A类。本来代表A类的this指向了子类B,成为了多态。
// }                                            
 int fun2()
 {
  return 456;
 }
}
public class Demo3 {
 public static void main(String[] args) {
  A a;
  B b = new B();
  b.fun1();
//  a=b;
//  a.fun1();
 }
}




原创粉丝点击