package add;
import java.util.*;
class Rectangle{ //不需要添加public
double length;
double width;
public Rectangle(){} //有无不重要
public Rectangle(double length,double width){ //构造函数
this.length=length;
this.width=width;}
public double area(double length,double width){ //重写方法
double Area=length*width;
return Area;
}
public void showInfo(){
System.out.println("底面积Area="+length*width);
}
}
class Cuboid extends Rectangle{
double height;
public Cuboid(){}
public Cuboid(double length,double width,double height){
super(length,width);
this.height=height;
}
public double Volume(){
double volume=length*width*height;
return volume;
}
public void showInfo(){
System.out.println("体积volume="+length*width*height);
}
}
public class test{
public static void main(String[] args){
Rectangle c2 = new Rectangle(3.1,4.2);
c2.showInfo();
Cuboid c1 = new Cuboid(3.1,4.2,5.3);
c1.showInfo();
}
}
如果不需要界面的话,只需要类和对象即可,先定义类再继承,再写计算面积方法
import java.util.HashMap;
public class 继承测试 {
/*
在该类中定义两个方法,一个是 getName,用于使用反射机制获得类名称;另一个是抽象方法 getArea ,用来计算图形的面积。
(2)创建圆形类 Circle ,继承自 Shape ,并实现抽象方法getArea。
在 Circle 类的构造方法中获得了圆形的半径,用于在getArea计算圆形的面积。
(3)创建矩形类 Rectangle ,继承自 Shape ,
并实现抽象方法 getArea 。在 Rectangle 类的构造方法中获得了矩形的长和宽,用于在 getArea计算矩形的面积。
*/
public static void main(String[] args) {
Shape circle= new Circle(10);
System.out.println("类名称是:"+circle.getName());
System.out.println("圆的面积="+circle.getArea());
Shape rect = new Rectangle(10,20);
System.out.println("类名称是:"+rect.getName());
System.out.println("矩形的面积="+rect.getArea());
}
}
abstract class Shape{
String getName() {
return this.getClass().getName();
}
abstract float getArea();
}
class Circle extends Shape{
float r;
public Circle() {};
public Circle(float r) {
this.r = r;
}
@Override
float getArea() {
return 3.14f*r*r;
}
}
class Rectangle extends Shape{
float width;
float height;
public Rectangle() {}
public Rectangle(float width,float height) {
this.width = width;
this.height = height;
}
@Override
float getArea() {
return width*height;
}
}
有偿的话,私信我帮你做
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps: 问答会员年卡【8折】购 ,限时加赠IT实体书,即可 享受50次 有问必答服务,了解详情>>>https://t.csdnimg.cn/RW5m