第8次作业--继承

题目:编写一个应用程序,创建一个矩形类,类中具有长、宽两个成员变量和求周长的方法。再创建一个矩形类的子类——正方形类,类中定义求面积方法、重写求周长的方法。在主类中,输入一个正方形边长,创建正方形对象,求正方形的面积和周长。(注意:所有类均在一个包中)

代码及注释:

/** 创建了矩形类Rec有length和width两个成员变量,Perimeter方法用来计算矩形周长
     又创建了一个Square类继承Rec类,area方法利用平方公式来计算面积,然后重写了Perimeter方法计算周长
     主类中创建了子类对象并赋值调用子类中的方法计算周长和面积*/
package Rectangular0924;
import java.util.*;
class Rec{
    int length;
    int width;
    int Perimeter() {
        return 2*(length+width);
    }
}
class Square extends Rec{
    int area() {
        return (int) Math.pow(length, 2);
    }
    int Perimeter() {
        return 4*length;
    }
}


public class Mainclass {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("输入正方形边长:");
        Scanner reader = new Scanner(System.in);
        int length = reader.nextInt();
        Square a = new Square();
        a.length=length;
        System.out.println("正方形的面积为:"+a.area());
        System.out.println("正方形的周长为:"+a.Perimeter());        
    }
}

运行结果:

原文地址:https://www.cnblogs.com/xushaohua/p/11580977.html