抽象類
問:用final關(guān)鍵字可不可以修飾抽象類?
答:不可以
因為:
1,用final修飾的會變成常量,不能被更改;
2,用final修飾的方法不能被重寫
3,用final修飾的類不能被繼承
- 抽象類的一些用法:
// abstract 用來修飾抽象類
// 抽象類中可以定義非抽象方法和屬性
// 抽象類是不可以實例化的
// 抽象類的抽象方法必須實現(xiàn)
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();
//有構(gòu)造方法
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函數(shù)中的實現(xiàn):
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());
}