第七周编程总结

(一)抽象类的使用

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

2.编程技巧

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

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

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

 

源代码:

package Seven;

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 Rectangular extends shape {
    private double width;
    private double height; 
    public Rectangular(double width, double height){
        this.height=height;
        this.width=width;    
    }
    public double print() {      
        return width*height;  
    }
}

class Round extends shape {
    double r;     
    public Round(double r){  
        this.r=r;  
    }
    public double print() {     
        return Math.PI*r*r;
    }
}
public class Test {
    public static void main(String[] args){
        shape s1=new Triangle(2,3,4);
        shape s2=new Rectangular(2,4);
        shape s3=new Round(3);     
        System.out.println("三角形的面积为: "+s1.print());
        System.out.println("矩形的面积为: "+s2.print());
        System.out.println("圆的面积为: "+s3.print());
}
}

运行截屏:

 

(二)使用接口技术

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

  1. 编程技巧

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

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

源代码:

package demo;
public interface Shape {
    public abstract void size(); 
}
class Linux implements Shape{   
    private double x;
    public Linux(double x){  
        this.x=x;     
    }
    public void size() {  
        System.out.println("直线的长度: "+x);
    }
}
class Round implements Shape{
    private double r;
    public Round(double r){    
        this.r=r;        
    }
    public void size(){    
        System.out.println("圆的面积: "+Math.PI*r*r);
    }
}
package demo;

public class Test2 {
    public static void main(String[] args){
        Shape s1=new Linux(7);
        Shape s2=new Round(3);   
        s1.size();
        s2.size();
    }
}

运行截屏:

 

总结:

(1)学了size方法和接口问题。
(2)学习了新的关键词abstract(object且为最大的父类)

posted on 2019-10-12 20:27  Bowen158  阅读(148)  评论(0编辑  收藏  举报

导航