2020.8.25收获
学习内容
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+"米"+"\n体重"+weight+"千克\n"+"尾巴:"+tail+"米\n");
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 }



浙公网安备 33010602011771号