资源描述
第4章 类和对象的高级特征
第4章 类和对象的高级特征
【实验目标】
完成本章的内容以后,您将达到:
u 理解类和对象
u 理解抽象和封装
u 理解对象与类之间的关系
u 掌握包的创建和导入本章实验给出了全面的操作步骤,请学生按照给出的步骤独立完成实验,以达到要求的实验目标。
· 第一阶段——指导学习(40分钟)
1. 编写一个Demo.java,编译并运行
1) 建立文件名为“Demo.java”,输入以下程序代码。[注意:Java文件名必须与用public 修饰的类名保持一致]
package com.imti.study;
/**
* 超类Box
* @1.0版 2008年7月27日
* @author xx
*/
class Box {
double width;
double height;
double depth;
/**
*构造方法重载
*/
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
/**
*构造方法重载
*/
Box(double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}
}
/**
* BoxWeight继承类Box
* @1.0版 2008年7月27日
* @author xx
*/
class BoxWeight extends Box {
double weight;
/**
*构造方法重载
*/
BoxWeight(double w, double h, double d,double m)
{
super(w,h,d);
weight=m;
}
/**
*构造方法重载
*/
BoxWeight(double len,double m)
{
super(len);
weight=m;
}
/**
*方法重写
*/
double volume() {
return width + height + depth;
}
}
/**
* BoxCost继承类BoxWeight
* @1.0版 2008年7月27日
* @author xx
*/
class BoxCost extends BoxWeight {
double cost;
/**
*构造方法重载
*/
BoxCost(double w,double h,double d,double m,double c)
{
super(w,h,d,m);
cost=c;
}
/**
*构造方法重载
*/
BoxCost(double len,double m,double c)
{
super(len,m);
cost=c;
}
/**
*方法重写
*/
double volume() {
return width*2;
}
}
/**
* Demo测试类
* @1.0版 2008年7月27日
* @author xx
*/
public class Demo{
public static void main(String args[]) {
BoxCost cost1=new BoxCost(10,18,16,8,18.9);
double vo1=cost1.volume();
System.out.println("Weight of BoxCost is:"+cost1.weight);
System.out.println("Cost of BoxCost is:"+cost1.cost);
System.out.println("Volume of BoxCost is:"+vo1);
}
}
2)编译并运行。
第二阶段——练习(40分钟)
习题一
有一个汽车类Vehicle,该类有两个属性name(名字),color(颜色),和一个void drive()方法,有两个类Bus和Car分别继承于Vehicle,要求分别在各自的构造方法中通过super调到父类的构造方法,并重写父类的void drive()方法.通过main方法进行测试.
展开阅读全文