抽象方法、抽象类的用法

1、抽象方法:由abstract修饰(只有方法的定义),没有方法体的

2、抽象类:由abstract 修饰,可以有抽象方法和普通方法

3、包含抽象方法的类,必须是抽象类

4、抽象类不能被实例化,一般需要继承。

5、继承后1)、子类也声明为抽象类

2)、子类重写抽象类中的所有抽象方法

6、类中没有抽象方法。也可以将类声明抽象类

abstract class Shape1{ double c ; abstract double area(); }

class Square1 extends Shape { Square1(double c){ this.c = c; } double area(){ return 0.0625*c*c; } }

class Circle1 extends Shape{ Circle1(double c){ this.c = c; } double area(){ return 0.0796*c*c; } } 这是个小例子,最大数的面积

public static void main(String[] args) {

Shape[] shapes = new Shape[2];

shapes[0] = new Circle(2);

shapes[1] = new Square1(4);

max(shapes);

}

public static void max(Shape[] shapes){

double max = shapes[0].area();

int maxIndex = 0;

for(int i = 0;i<shapes.length;i++){

double area = shapes[i].area();

if(area>max){

maxIndex = i;

}

}

System.out.println("max:"+max);

}

}


public static void main(String[] args) { Shape[] shapes = new Shape[2]; shapes[0] = new Circle(2); shapes[1] = new Square1(4); max(shapes); } public static void max(Shape[] shapes){ double max = shapes[0].area(); int maxIndex = 0; for(int i = 0;i max){ maxIndex = i; } } System.out.println("max:"+max); } }
经验分享 程序员 微信小程序 职场和发展