Java利用重写的方式计算不同形状的面积和周长
程序员文章站
2022-04-15 17:56:44
遇到的问题:Implicit super constructor Rectangle() is undefined. Must explicitly invoke another constructor问题来源:长方形类里面缺少默认构造函数...
遇到的问题:Implicit super constructor Rectangle() is undefined. Must explicitly invoke another constructor
问题来源:长方形类里面缺少默认构造函数。
问题分析:
Square继承了Rectangle,那么在构造Square之前,就会先构造Rectangle。如果Square没有人为指定的构造函数,在创建对象时调用的是默认的构造函数,而子类默认的构造函数调用的也是父类默认的构造函数。如果父类有了人为指定的构造函数,就会覆盖本身自动生成的默认的无参构造函数,换言之,父类没有了无参构造函数,就会报错。这里值的注意的是,不管子类的构造函数是什么样的形式,都会默认调用父类的默认无参构造函数。
package com.spaceshell.override.questions;
import static java.lang.Math.PI;
/**
* @Description 方法重写的应用
* @author Jesse
* @time 2020-11-19 18:04:43
*/
public class TestShape {
public static void main(String[] args) {
Circle circle = new Circle(5.0);
System.out.println("圆形面积为:" + circle.area());
System.out.println("圆形周长为:" + circle.girth());
Rectangle rectangle = new Rectangle(2.3, 4.5);
System.out.println("长方形面积为:" + rectangle.area());
System.out.println("长方形周长为:" + rectangle.girth());
Square square = new Square(3.6);
System.out.println("正方形面积为:" + square.area());
System.out.println("正方形周长为:" + square.girth());
}
}
/**
* 图形父类
* 只是定义了任何图形都应具有计算面积和周长的方法
*/
class Shape{
public double area() {
return 0.0;
}
public double girth() {
return 0.0;
}
}
//圆形
class Circle extends Shape{
private double radius; //属性 半径
//有参构造方法
public Circle(double radius) {
this.radius = radius;
}
public double area() {
return PI*radius*radius;
}
public double girth() {
return 2*PI*radius;
}
}
//长方形
class Rectangle extends Shape{
private double length;
private double width;
public Rectangle() {}
public Rectangle(double length,double width) {
this.length = length;
this.width = width;
}
public double area() {
return length*width;
}
public double girth() {
return 2*(length+width);
}
}
//正方形
class Square extends Rectangle{
private double side;
public Square(double side) {
this.side = side;
}
public double area() {
return side*side;
}
public double girth() {
return 4*side;
}
}
鸣谢:https://blog.csdn.net/dlf123321/article/details/53411539
本文地址:https://blog.csdn.net/spaceshell/article/details/109822840