2020.8.18

一、今日学习内容

   1、定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square。

 1 //Shape类:
 2 public abstract class Shape {
 3     public abstract void getArea();
 4 }
 5 //Rectangle类:
 6 public class Rectangle extends Shape{
 7     private float l,w;
 8     Rectangle(float l1,float w1){
 9         l=l1;
10         w=w1;
11     }
12     public void getArea() {
13         float a;
14         a=l*w;
15         System.out.println("形状:矩形");
16         System.out.println("该图形面积为:"+a);
17     }
18 }
19 //Circle类:
20 public class Circle {
21     private float r;
22     Circle(float r1){
23         r=r1;
24     }
25     public void getArea() {
26         float a;
27         a=(float)3.14*r*r;
28         System.out.println("形状:圆形");
29         System.out.println("该图形的面积为:"+a);
30     }
31 }
32 //Square类:
33 public class Square extends Rectangle {
34     Square(float a){
35         super(a,a);
36     }
37 }
38 //测试类:
39 import java.util.*;
40 public class Test2 {
41     public static void main(String[] args) {
42         float x,y,r;
43         System.out.println("请输入边长:");
44         Scanner con=new Scanner(System.in);
45         x=con.nextFloat();
46         y=con.nextFloat();
47         Rectangle rec=new Rectangle(x,y);
48         rec.getArea();
49         System.out.println("请输入半径:");
50         r=con.nextFloat();
51         Circle cir=new Circle(r);
52         cir.getArea();
53     }
54 }

 

  2、定义一个哺乳动物类Mammal,再由此派生出狗类Dog,定义一个Dog类的对象,观察基类和派生类的构造函数的调用顺序。

 1 //基类:Mammal类
 2 public class Mammal {
 3     protected float weight,height;
 4     Mammal(float w,float h){
 5         weight=w;
 6         height=h;
 7         System.out.println("Mammal类构造函数");
 8     }
 9 }
10 //派生类:Dog类
11 public class Dog extends Mammal{
12     private float tail;
13     Dog(float w,float h,float t){
14         super(w,h);
15         tail=t;
16         System.out.println("Dog类构造函数");
17     }
18     public void show() {
19         System.out.println("身高:"+height+"米"+"
体重"+weight+"千克
"+"尾巴:"+tail+"米
");
20     }
21 
22     public static void main(String[] args) {
23         Dog x=new Dog((float)15,(float)0.8,(float)0.2);
24         x.show();
25     }
26 }

 

  3、定义一个Document类,有数据成员name,从Document派生Book类,增加数据成员pageCount。

 1 //Document类:
 2 public class Document {
 3     protected String name;
 4     Document(String n){
 5         name=n;
 6     }
 7 }
 8 //Book类:
 9 public class Book extends Document {
10     private int pageCount;
11     Book(String n,int p){
12         super(n);
13         pageCount=p;
14     }
15     public void show() {
16         System.out.println("文件名:"+name+"
页数:"+pageCount);
17     }
18 
19     public static void main(String[] args) {
20         Book a=new Book("书",100);
21         a.show();
22     }
23 }

 

二、遇到的问题

   对第一个题目的题目开始没有理解清楚

三、明日计划

  继续完成相关例题

原文地址:https://www.cnblogs.com/wmdww/p/13525709.html