一、今日学习内容
1、定义一个哺乳动物类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 }
2、定义一个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+"\n页数:"+pageCount);
17 }
18
19 public static void main(String[] args) {
20 Book a=new Book("书",100);
21 a.show();
22 }
23 }
3、定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square。
//Shape类: public abstract class Shape { public abstract void getArea(); } //Rectangle类: public class Rectangle extends Shape{ private float l,w; Rectangle(float l1,float w1){ l=l1; w=w1; } public void getArea() { float a; a=l*w; System.out.println("形状:矩形"); System.out.println("该图形面积为:"+a); } } //Circle类: public class Circle { private float r; Circle(float r1){ r=r1; } public void getArea() { float a; a=(float)3.14*r*r; System.out.println("形状:圆形"); System.out.println("该图形的面积为:"+a); } } //Square类: public class Square extends Rectangle { Square(float a){ super(a,a); } } //测试类: import java.util.*; public class Test2 { public static void main(String[] args) { float x,y,r; System.out.println("请输入边长:"); Scanner con=new Scanner(System.in); x=con.nextFloat(); y=con.nextFloat(); Rectangle rec=new Rectangle(x,y); rec.getArea(); System.out.println("请输入半径:"); r=con.nextFloat(); Circle cir=new Circle(r); cir.getArea(); } }
二、遇到的问题
无。
三、明日计划
继续完成相关例题的验证。
