java - day12 - ShapeTest
抽象类的定义及使用
抽象类不能实例化,但抽象类名的数组类型可以,见案例
1 package com.example; 2 3 4 public class ShapeTest { 5 public static void main(String[] args){ 6 Shape[] shapes = new Shape[3]; //shape为抽象类,不可以实例化;shape[]为数组类,可以实例化 7 shapes[0] = new Square(3.1); 8 shapes[1] = new Circle(1.5); 9 shapes[2] = new Circle(2.4); 10 ShapeTest x = new ShapeTest(); 11 System.out.println(x.areaMax(shapes)); 12 } 13 14 double areaMax(Shape[] shapes){ 15 double areamax = shapes[0].area(); 16 for(int i=0;i<shapes.length;i++){ 17 double max = shapes[i].area(); 18 if(max>areamax){ 19 areamax = max; 20 } 21 } 22 return areamax; 23 } 24 } 25 26 abstract class Shape{ 27 double a; 28 abstract double area(); 29 } 30 31 //子类继承父类抽象方法--重写 32 class Square extends Shape{ 33 Square(double a){ 34 this.a = a; 35 } 36 } 37 @Override 38 double area(){ 39 return 0.0625*a*a; 40 } 41 } 42 43 class Circle extends Shape{ 44 Circle(double a){ 45 this.a = a; 46 } 47 @Override 48 double area(){ 49 return 0.0796*a*a; 50 } 51 }