第八次作业--继承

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

一.源代码

package 啦啦啦;//创建一个包
import java.util.*;//导入整个包
class Rectangle1 {
    int length;
    int width;//两个成员变量
    int perimter(){
        return (length+width)*2;//求长方形的周长
    }
}
class square extends Rectangle1{
    int  area(){
        return length*length;
    }
    int  perimter(){
        return length*4;//重写
}
}
public class T2{
public static void main(String[]args){
     square T=new  square();//创建一个对象
     Scanner reader=new Scanner(System.in);//利用scanner类创建对象
     System.out.println("请输入正方形的长");//输出语句
     T.length=reader.nextInt();//使用对象reader接收数据length
     System.out.println("这个正方形的面积为"+T.area());//输出正方形面积
     System.out.println("这个正方形的周长为"+T.perimter());//输出正方形周长
}}

二.运行截图

原文地址:https://www.cnblogs.com/912760869-qq/p/11581604.html