题目:
编写一个应用程序,创建一个矩形类,类中具有长、宽两个成员变量和求周长的方法。再创建一个矩形类的子类——正方形类,类中定义求面积方法、重写求周长的方法。在主类中,输入一个正方形边长,创建正方形对象,求正方形的面积和周长。(注意:所有类均在一个包中)
Rectangle.java
1.创建一个Rectangle类,类中含有长和宽两个成员变量,定义了求周长的方法
2.创建Rectangle类的子类——Square类,类中定义了求面积的方法,重写求周长的方法
1 package aaa; 2 3 public class Rectangle { //父类Rectangle 成员变量length表示长度 成员变量width表示宽度 4 public int length; 5 public int width; 6 int getPerimeter(int length,int width){ //求周长的方法 7 this.length=length; 8 this.width=width; 9 int perimeter=(length+width)*2; 10 return perimeter; 11 } 12 13 } 14 class Square extends Rectangle{ //子类Square继承父类Rectangle 15 int getArea(int length,int width){ //定义求面积的方法 16 this.length=length; 17 this.width=width; 18 return length*width; 19 } 20 int getPerimeter(int length,int width){ //重写求周长的方法 21 this.length=length; 22 this.width=width; 23 return (length+width)*2; 24 } 25 }
Test.java
1.在主类Test中,创建正方形对象,输入一个正方形边长,求正方形的面积和周长
1 package aaa; 2 3 import java.util.Scanner; 4 5 public class Test { 6 public static void main(String[] args) { 7 Scanner sc=new Scanner(System.in); 8 System.out.println("请输入正方形边长:"); 9 int a=sc.nextInt(); 10 Square s=new Square(); //创建Square类的s对象 11 System.out.println("正方形的面积为:"+s.getArea(a, a)); //调用s对象的求面积的方法 12 System.out.println("正方形的周长为:"+s.getPerimeter(a, a));//调用s对象的求周长的方法 13 } 14 15 }
运行结果: