第七周课程总结&实验报告(五)

(一)抽象类的使用

  1. 设计一个类层次,定义一个抽象类--形状,其中包括有求形状的面积的抽象方法。 继承该抽象类定义三角型、矩形、圆。 分别创建一个三角形、矩形、圆存对象,将各类图形的面积输出。
    注:三角形面积s=sqrt(p*(p-a)*(p-b)*(p-c)) 其中,a,b,c为三条边,p=(a+b+c)/2

2.编程技巧

(1)    抽象类定义的方法在具体类要实现;

(2)    使用抽象类的引用变量可引用子类的对象;

(3) 通过父类引用子类对象,通过该引用访问对象方法时实际用的是子类的方法。可将所有对象存入到父类定义的数组中。

1.代码源

package 实验报告5;



abstract class shape{
    public abstract double print();    //定义抽象方法
}
class Triangle extends shape{
    private double a;
    private double b;
    private double c;
    public Triangle(double a,double b,double c){
        this.a=a;
        this.b=b;
        this.c=c;
    }
    public double print(){
        double p=(a+b+c)/2;
        return Math.sqrt(p*(p-a)*(p-b)*(p-c));
    }
}
class Rectangle extends shape{
    private double height;
    private double width;
    public Rectangle(double height,double width){
        this.height=height;
        this.width=width;
    }
    public double print(){
        return height*width;
    }
}
class yuan extends shape{
    private double radius;
    public yuan(double radius){
        this.radius=radius;
    }
    public double print(){
        return Math.PI*Math.pow(radius, 2);
    }
}
   public  class 实验报告5{
    public static void main(String[] args){
        Triangle Tr=new Triangle(8,9,10);
        Rectangle Re=new Rectangle(4,5);
        yuan yu=new yuan(6);
        System.out.println("三角形的面积:"+Tr.print());
        System.out.println("矩形的面积:"+Re.print());
        System.out.println("圆的面积:"+yu.print());
    }
}

 结果图

(二)使用接口技术

1定义接口Shape,其中包括一个方法size(),设计“直线”、“圆”、类实现Shape接口。分别创建一个“直线”、“圆”对象,将各类图形的大小输出。

  1. 编程技巧

(1) 接口中定义的方法在实现接口的具体类中要重写实现;

(2) 利用接口类型的变量可引用实现该接口的类创建的对象。

1.代码源

package 实验;

  public  interface Shape {
      double size();
 
}
 class Line implements Shape{
     private double x1,y1,x2,y2;
     public Line(double x1,double y1,double x2,double y2){
         this.x1=x1;this.y1=y1;
         this.x2=x2;this.y2=y2;
     }
     public double size(){
         return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
     }
 }
 class Circle implements Shape{
     private double r;
    public void Cricle (double r){
         this.r=r;
     }
     public double size (){
         return 3.14*r*r;
     }
 }
     public   class  Shape{
     public static void main(String args[]){
         Shape Line,Circle;
         Line Li =new Line (22,56,41,57);
         Circle Ci =new Circle (47);
         System.out.println(Line.size());
         System.out.println(Circle.size());
     }
 }

总结

我感觉好难。。。。

还有一个不会,中间有点难

但我感觉学会了接口。

原文地址:https://www.cnblogs.com/Allen15773771785/p/11650802.html