Java第八次作业
一.题目:编写一个应用程序,创建一个矩形类,类中具有长、宽两个成员变量和求周长的方法。再创建一个矩形类的子类——正方形类,类中定义求面积方法、重写求周长的方法。在主类中,输入一个正方形边长,创建正方形对象,求正方形的面积和周长。(注意:所有类均在一个包中)
二.代码及注释
/**创建矩形类,定义成员变量长,宽,方法。
创建子类Square,继承Rectangle类,并定义求正方形面积的方法和重写求周长的方法。
主类中输入正方形边长,创建对象并输出正方形的面积和周长。
*/
import java.util.*; //Rectangle矩形类 class Rectangle{ double height; double width; public double Girth(){ double girth=height*2+width*2; return girth; } } //Square正方形类 class Square extends Rectangle{ public double Area(){ return height*height; } public double Girth(){ return height*4; } } //Inherit主类 public class Inherit { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请输入正方形边长:"); Scanner se = new Scanner(System.in); double i=se.nextDouble(); Square s = new Square();
s.height=i; System.out.println("正方形面积是:"+s.Area()); System.out.println("正方形周长是:"+s.Girth()); } }
三.结果截图