定义—个类MyRectangle代表矩形,为矩形定义getLength方法(获得矩形的长度)、getWidth方法(获得矩形的宽度)、setLength方法(设置矩形的长度)、setWidth方法(设置矩形的宽度)、getArea方法(求矩形的面积)和toString方法(显示矩形的格式),为矩形派生出一个子类MySquare代表正方形,并对getArea和toString进行重写。并编写程序进行测试。
package project01;
import java.util.Scanner;
class MyRectangle{
private double length;
private double width;
//封装
public double getlength() {
return this.length; //长
}
public void setlength(double length) {
this.length=length;
}
public double getwidth() {
return this.width; //宽
}
public void setwidth(double width) {
this.width=width;
}
//创建构造方法
public MyRectangle(double width ) {
this.width=width;
}
public MyRectangle(double length,double width ) {
this.length=length;
this.width=width;
}
public void getArea() { //计算面积
System.out.println("长方形的面积:"+length*width);
}
public void toArea(){ //格式
System.out.println("长方形的格式:长x宽="+length*width);
}
}
class MySquare extends MyRectangle { //子类MySquare继承父类MyRectangle
public MySquare() {
super(5.0); //父类中没有无参的构造方法,用super关键字来显示的调用父类中的有参构造方法
}
public MySquare(double m) {
super(m);
}
//方法的重写
public void getArea() {
System.out.println("正方形的面积:"+this.getwidth()*this.getwidth()); //继承的是封装里的内存。
}
public void toArea(){
System.out.println("正方形的格式:边长x边长="+this.getwidth()*this.getwidth());
}
}
public class Lianxiti {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//长方形
System.out.println("输入长方形的长:");
double c=input.nextDouble();
System.out.println("输入长方形的宽:");
double k=input.nextDouble();
MyRectangle t=new MyRectangle(c,k);
t.getArea();
t.toArea();
//正方形
System.out.println("输入正方形的边长:");
double m=input.nextDouble();
MySquare p= new MySquare();
p.setwidth(m);
p.getArea();
p.toArea();
input.close();
}
}
运行结果: