抽象类

抽象类

问:用final关键字可不可以修饰抽象类?
答:不可以
因为:
1,用final修饰的会变成常量,不能被更改;
2,用final修饰的方法不能被重写
3,用final修饰的类不能被继承

  • 抽象类的一些用法:
//  abstract  用来修饰抽象类
//  抽象类中可以定义非抽象方法和属性
//  抽象类是不可以实例化的
//  抽象类的抽象方法必须实现
abstract class Shape {
    private String name;
    //也可以有非抽象方法
    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return this.name;
    }
    
    abstract double bc();
    abstract double area();
    //有构造方法
    public Shape() {
        this.name = name;
    }
    
    public Shape(String name) {
        this.name = name;
    }
}

class Square extends Shape {
    //正方形有边长
    double sideLength;
    
    @Override   //周长
    double bc() {
        return this.sideLength * 4;
    }

    @Override   //面积
    double area() {
        return this.sideLength * this.sideLength;
    }   
    
    public Square() {
        
    }
    
    public Square (String name,double sideLength) {
        this.setName(name);
        this.sideLength = sideLength;
        
    }
}
class Rectangular extends Shape {
    double length;
    double width;
    @Override
    double bc() {
        return (this.length + this.width) * 2;
    }
    @Override
    double area() {
        return this.length * this.width;
    }
    
    public Rectangular() {
        
    }
    public Rectangular(int length,int width,String name) {
        super(name);
        this.length = length;
        this.width = width;
    }
    
}

//没有抽象方法也可以定义抽象类
abstract class a {
    public void func(){
        
    }
}
  • main函数中的实现:
public static void main(String[] args) {
        Square square = new Square("aa",10);
        double area = square.area();
        System.out.println("squ的名字" + square.getName() + "面积为" + area);
        
        Rectangular rect = new Rectangular(10,12,"bb");
        System.out.println("rect的名字" + rect.getName() + "面积为" + rect.area());
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容