– 在包bzu.aa中定义一个交通工具类(Vehicle):
Vehicle类:
package bzu.aa;
public class Vehicle{
public int capacity;
Vehicle(){
capacity=2;
System.out.println("执行交通工具类的无参构造方法");
}
public Vehicle(int c){
this.capacity=c;
System.out.println("执行交通工具类的有参构造方法");
}
void setCapacity(int capacity){
this.capacity=capacity;
}
int getCapacity(){
return capacity;
}
public void print(){
System.out.println("载客量为:"+capacity);
}
}
Car类:
package bzu.aa;
public class Car extends Vehicle{
public int speed;
public Car(){
speed=0;
System.out.println("执行汽车类的无参构造方法");
}
public Car(int s){
super(5);
speed=s;
System.out.println("执行汽车类的有参构造方法");
}
public int speedUp(){
speed=speed+10;
return speed;
}
public int speedDown(){
speed=speed-15;
return speed;
}
public void print(){
System.out.println("载客量:"+capacity+",速度为:"+speed);
}
}
Bus类:
package bzu.bb;
import bzu.aa.Car;
public final class Bus extends Car{ //Bus类继承Car类,同时继承了Car类的所有的成员变量和方法
int capacity;
public Bus(){
capacity=20;
System.out.println("执行公交车类的无参构造方法");
}
Bus(int capacity) {
super(5); //调用父类的构造方法
this.capacity = capacity;
System.out.println("执行公交车类的有参构造方法");
}
public void print(){
System.out.println("载客量:"+super.capacity+",速度为:"+speed+"载客量:"+capacity);
}
}
Test类:
package bzu.bb;
import bzu.aa.Car;
public class Test {
public static void main(String[] args) {
Car car = new Car();
while(car.speed<50)
car.speedUp();
car.print();
while(car.speed>20)
car.speedDown();
car.print();
Bus bus = new Bus();
bus.print();
}
}
运行结果:
程序分析:
这个题目运用的是继承,用extends关键字可以实现子类对父类的继承,继承父类的所有成员变量还有方法,super()关键字可以继承父类的构造方法,但需要放在子类构造方法的第一句,在子类中写与父类方法名参数全部都一样的方法是实现父类这个方法的重写,运行的时候父类的这个方法将会被隐藏,执行子类的这个方法,变量也是一样的,继承主要是为了优化程序,将重复的代码写入父类中,不同的子类去继承使用就好了,而不需要再重复的书写代码。