Java继承练习

需求:

分析以下需求用代码实现:

  1. 定义形状类:

    功能:求面积,求周长

  2. 定义圆形类Round:

    属性:半径,圆周率

    功能:求面积,求周长

  3. 定义长方形类Rectangle:

     属性:长和宽
    

    功能:求面积,求周长

  4. 定义测试类:

     分别创建圆形和长方形对象,为相应的属性赋值
    

    分别调用求面积和求周长的方法

代码演示:

//形状类
public abstract class Shape {  
    public abstract void area();  
  
    public abstract void girth();  
}

//圆
public class Round extends Shape {  
    private double radius;  
    private double Pi;  
  
    public Round() {  
    }  
  
    public Round(double radius, double pi) {  
        this.radius = radius;  
        Pi = pi;  
    }  
  
    public double getRadius() {  
        return radius;  
    }  
  
    public void setRadius(double radius) {  
        this.radius = radius;  
    }  
  
    public double getPi() {  
        return Pi;  
    }  
  
    public void setPi(double pi) {  
        Pi = pi;  
    }  
  
    @Override  
    public void area() {  
        double roundArea = 0;  
        roundArea = radius * radius * Pi;  
        System.out.println("圆的面积:" + roundArea);  
    }  
  
    @Override  
    public void girth() {  
        double roundGirth = 0;  
        roundGirth = 2 * radius * Pi;  
        System.out.println("园的周长:" + roundGirth);  
    }  
}

//长方形
public class Rectangle extends Shape {  
    private double length;  
    private double wide;  
  
    public Rectangle() {  
    }  
  
    public Rectangle(double length, double wide) {  
        this.length = length;  
        this.wide = wide;  
    }  
  
    public double getLength() {  
        return length;  
    }  
  
    public void setLength(double length) {  
        this.length = length;  
    }  
  
    public double getWide() {  
        return wide;  
    }  
  
    public void setWide(double wide) {  
        this.wide = wide;  
    }  
  
    @Override  
    public void area() {  
        double rectangleArea = 0;  
        rectangleArea = length * wide;  
        System.out.println("长方形的面积:" + rectangleArea);  
    }  
  
    @Override  
    public void girth() {  
        double rectangleGirth = 0;  
        rectangleGirth = (2 * length) + (2 * wide);  
        System.out.println("长方形的周长:" + rectangleGirth);  
    }  
}

//测试类
public class Test {  
    public static void main(String[] args) {  
        Round rd = new Round(1,3.14);  
        Rectangle re = new Rectangle(5,4);  
        rd.area();  
        rd.girth();  
        re.area();  
        re.girth();  
    }  
}

你可能感兴趣的:(Java,java,开发语言)