java笔记 抽象类

一.使用范围

抽象类里面 可以有非抽象的方法
抽象类里面 可以没有抽象方法
抽象类 不能实例化对象
一个类里面有抽象方法的话,该类必须是抽象类
抽象方法 一定不能实现方法

二.例子

abstract class Geometry  // 抽象类 底
{
    
    
    public abstract double getArea();
}

class Circle extends Geometry  // 继承抽象类 圆
{
    
    
    double r;

    Circle(double r)
    {
    
    
        this.r = r;
    }

    public double getArea()
    {
    
    
        return (3.14 * r * r);
    }
}

class Rectabgle extends Geometry  // 继承抽象类 矩形
{
    
    
    double a;
    double b;

    Rectabgle()
    {
    
    
        a = 0;
        b = 0;
    }

    Rectabgle(double a, double b)
    {
    
    
        this.a = a;
        this.b = b;
    }

    public double getArea()
    {
    
    
        return a * b;
    }
}

class Pillar  // 定义柱类,用来计算他的体积
{
    
    
    Geometry bottom;  // 定义一个抽象类 作为底 最后用具体的子类底给他赋值
    double height;
    Pillar(Geometry bottom, double height)
    {
    
    
        this.bottom = bottom;
        this.height = height;
    }

    public double getVolume()
    {
    
    
        if(bottom == null)
        {
    
    
            System.out.println("无底,不能计算面积");
            return -1;
        }

        return bottom.getArea() * height; // 这个时候底已经被实例化了
    }
}

public class test
{
    
    
    public static void main(String args[])
    {
    
    
        Pillar pillar;
        Geometry bottom = null;

        pillar = new Pillar(bottom, 100); //定义一个无底柱
        System.out.println("体积: " + pillar.getVolume());

        bottom = new Rectabgle(12 ,22);
        pillar = new Pillar(bottom, 58);  // 定义一个矩形底的柱形
        System.out.println(pillar.getVolume());

        bottom = new Circle(10);
        pillar = new Pillar(bottom, 58); // 定义一个圆形底的柱形
        System.out.println(pillar.getVolume());
    }
}

这个例子中,我们定义一个抽象类Geometry几何Circle圆Rectabgle矩形继承这个抽象类
Geometry几何用来实现面积的计算,但是不需要实现函数
因为在后面的圆和矩形的面积计算方法都不一样,只要在他们类里面分别实现就可以了

然后我们写一个Pillar柱类,用来实现计算体积

在主类里面,我们定义一个柱类,一个底类(用Geometry几何实例化)

将定义出来的圆和矩形赋值给bottom,这个就是上转型对象,它可以调用改写过的getArea()函数,再将bottom带入Pillar类中,计算出体积

在这里插入图片描述


如果我们不适用抽象类的话,在类pillar中我们就要预设好底是什么,如果临时改变了底的话,还要修改这个pillar类。

不然只需要添加这个底的类就ok了

猜你喜欢

转载自blog.csdn.net/yogur_father/article/details/108855857