第七周

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

实验四 类的继承

  • 实验目的
  • 理解抽象类与接口的使用;
  • 了解包的作用,掌握包的设计方法。
  • 实验要求
  • 掌握使用抽象类的方法。
  • 掌握使用系统接口的技术和创建自定义接口的方法。
  • 了解 Java 系统包的结构。
  • 掌握创建自定义包的方法。

  • 实验内容

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

2.编程技巧

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

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

(3) 通过父类引用子类对




package 五;

abstract class shape {
    public abstract double print();   
}
class s extends shape { 
    private double a;
    private double b;
    private double c;         
    public s(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 j extends shape {
    private double width;
    private double height; 
    public j(double width, double height){
        this.height=height;this.width=width;    
    }
    public double print() {      
        return width*height;  
    }
}
class y extends shape {
    double banjing;     
    public y(double banjing){  
        this.banjing=banjing;  
    }
    public double print() {     
        return Math.PI*banjing*banjing;
    }
}
package 五;

public class test {
     public static void main(String[] args){
          shape s1=new s(3,6,8);
          shape s2=new j(5,10);
          shape s3=new y(5);     
          System.out.println("三角形的面积为: "+s1.print()+"矩形的面积为: "+s2.print()+"圆的面积为: "+s3.print());     
     }
}

 

 

2

package test;

public interface Shape {
    public double size();
}

class Line implements Shape{
    double x1,x2,y1,y2;
    public Line (double x1, double x2, double y1, double y2) {
        this.x1 = x1; this.x2 = x2;
        this.y1 = y1; this.y2 = y2;
    }
    public double size() {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }
}

class Circle implements Shape{
    double r;
    public Circle(double r) {
        this.r = r;
    }
    public double size() {
        return Math.PI * r * r;
    }
}



package test;

public class Six {
    public static void main (String args[]) {
        Line l = new Line(10,20,30,40);
        Circle c = new Circle(50);
        System.out.println("直线的长度:"+l.size());
        System.out.println("圆的面积:"+c.size());
    }
}

 

1.抽象类和接口都不能直接实例化,

2.抽象类必须通过对象的多态性进行实例化操作,且抽象类要被子类继承,接口要被类实现。

posted @ 2019-10-12 21:09  徐卓韩  阅读(148)  评论(0编辑  收藏  举报