几个点:
重载方法:要求子类中的方法 参数要和Super不同
覆盖方法:返回值类型 方法名 参数 都要和Super相同
/*
Online Java - IDE, Code Editor, Compiler
Online Java is a quick and easy tool that helps you to build, compile, test your programs online.
*/
abstract class Shape{
String name;
public Shape(){}
public Shape(String name){
this.name = name;
}
public abstract double getS();
public abstract double getC();
}
class Circle extends Shape{
private double radius;
public Circle(){
this(0.0);
}
public Circle(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
@Override
public double getC(){
return 2.0*Math.PI * radius;
}
@Override
public double getS(){
return Math.PI * radius * radius;
}
@Override
public String toString(){
return "[园] radius = "+ radius;
}
}
class Rectangle extends Shape{
private double radius;
public Rectangle(){
this(0.0);
}
public Rectangle(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
@Override
public double getC(){
return 4.0 * radius;
}
@Override
public double getS(){
return radius * radius;
}
@Override
public String toString(){
return "[正方形] radius = "+ radius;
}
}
public class Main
{
public static double Cal(Shape[] shapes){
double s = 0;
for(var shape : shapes){
System.out.println(shape.getS());
s = s + shape.getS();
}
return s;
}
public static void main(String[] args) {
var shapes = new Shape[5];
for(var i = 0; i < shapes.length; i++){
var d = Math.random();
if(d > 0.5)shapes[i] = new Circle(1);
else shapes[i] = new Rectangle(2);
}
var s_s = Cal(shapes);
System.out.printf("形状的总面积 = %.2f",s_s);
}
}