# 题目
编写一个应用程序,创建一个矩形类,类中具有长、宽两个成员变量和求周长的方法。
再创建一个矩形类的子类——正方形类,类中定义求面积方法、重写求周长的方法。
在主类中,输入一个正方形边长,创建正方形对象,求正方形的面积和周长。(注意:所有类均在一个包中)
## 源程序
## 矩形类
package Train.Method.TeachDemo.Forth; /** * 父类 - 矩形类 - 计算周长 * @author 喵 * @date 2019年9月24日下午5:47:31 */ public class Ractangle { public int longside; public int weightside; /** 计算周长*/ public int getprimeter() { return ((longside + weightside) * 2); } }
## 子类 - 正方形类
/** * 子类 - 正方形 - 周长面积 * @author 喵 * @date 2019年9月24日下午5:52:13 */ public class Square extends Ractangle { public Square(int longside, int weightside) { this.longside = longside; this.weightside = weightside; } public int getArea() { return (longside * longside); } @Override public int getprimeter() { return (longside * 4); } }
## 主方法 - 测试
import java.util.Scanner; /** * 测试正方形类的继承效果 * @author 喵 * @date 2019年9月24日下午7:40:56 */ public class SquareTest { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("请分别输入长和宽:"); int longside = input.nextInt(); int weightside = input.nextInt(); Square square = new Square(longside, weightside); System.out.println("正方形的面积为" + square.getArea()); System.out.println("正方形的周长为" + square.getprimeter()); } }
##运行结果