如果我把抽象类的抽象方法注释掉了;maxArea()里的.area()会报错;
shapes[0] = new Circle(1);完成向上构造;shapes[0].area();向上构造看引用类型;如果点的父类方法;那是不完整的;如果是指向对象的方法;父类又不能访问子类;
那么shapes[0].area();.的到底是谁的?为什么?抽象方法为什么是子类统一的入口?
请你帮我解释下好吗?
public class ShapeTest {
public static void main(String[] args) {
//Shape s = new Shape(); //编译错误,抽象类不能被实例化
Shape[] shapes = new Shape[4]; //创建Shape数组对象
shapes[0] = new Circle(1);
shapes[1] = new Circle(2); //大
shapes[2] = new Square(1);
shapes[3] = new Square(2);
maxArea(shapes);
}
//求数组的最大面积
public static void maxArea(Shape[] shapes){
double max = shapes[0].area();
int maxIndex = 0; //最大面积下标
for(int i=1;i<shapes.length;i++){
double area = shapes[i].area();
if(area>max){
max=area;
maxIndex=i;
}
}
System.out.println("最大面积为:"+max+",所在下标为:"+maxIndex);
}
}
abstract class Shape{ //抽象类
protected double c; //周长
public abstract double area(); //抽象方法
}
class Circle extends Shape{
public Circle(double c){
super.c = c;
}
public double area(){ //重写抽象方法
return 0.0796*c*c; //0.0625
}
}
class Square extends Shape{
public Square(double c){
super.c = c;
}
public double area(){
return 0.0625*c*c;
}
}
呼如林
呼啦一阵风
素胚勾勒不出你
相关分类