第8次作业--继承

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

代码:

1 /*编写一个应用程序,创建一个矩形类,类中具有长、宽两个成员变量和求周长的方法。*/
2 public class J {
3     int x;
4     int y;
5     int C (){
6         return (x+y)*2;
7     }
8 
9 }
 1 /*再创建一个矩形类的子类——正方形类,类中定义求面积方法,有参的构造方法、重写求周长的方法。 */
 2 public class Z extends J{
 3     int Area(){
 4         return x*x;        
 5     }
 6     int C (){
 7         return x*4;
 8     }
 9     Z(int x){
10         this.x =x;
11         
12     }
13 
14 }
 1 import java.util.Scanner;
 2 
 3 /* 在主类中,输入一个正方形边长,创建正方形对象,求正方形的面积和周长。*/
 4 public class test {
 5 
 6     /**
 7      * @param args
 8      */
 9     public static void main(String[] args) {
10         // TODO Auto-generated method stub
11         Scanner reader =new Scanner(System.in);
12          System.out.println("请输入正方形的边长:");
13             Z z=new Z(reader.nextInt());  
14             System.out.println("正方形的面积是:"+z.C());
15             System.out.println("正方形的周长是:"+z.Area());
16         
17 
18     }
19 
20 }

运行:

原文地址:https://www.cnblogs.com/When6/p/11580790.html