欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Lesson 3 上机练习题——继承

程序员文章站 2022-07-06 11:19:41
...
package bzu.aa;

public class Vehicle {
	
	int capacity;
	Vehicle()
	{
		capacity=2;
		System.out.println("执行交通工具类的无参构造方法");
	}
	Vehicle(int capacity )
	{
		this.capacity = capacity;
		System.out.println("执行交通工具的有参构造方法。");
	}
	public int getCapacity() {
		return capacity;
	}
	public void setCapacity(int capacity) {
		this.capacity = capacity;
	}
	
	void print()
	{
		System.out.println("[Vehicle]---capacity:"+capacity);
	}

}

package bzu.aa;

public class Car extends Vehicle{
	protected int speed;
	public Car()
	{
		super();
		speed =0;
		System.out.println("执行汽车类的无参构造方法。");
	}
	Car(int speed)
	{
		super();
		this.speed = speed;
		System.out.println("执行汽车类的有参构造方法。");
	}
	public int speedup()
	{
		speed+=10;
		return speed;
	}
	
	public int speeddown()
	{
		speed-=15;
		return speed;
	}
	public void print()
	{
		super.print();
		System.out.println("[Car]---speed:"+speed+",capacity:"+capacity);
	}

}



package bzu.bb;

import bzu.aa.Car;

public final class Bus extends Car{
	int capacity;
	Bus()
	{
		super();
		capacity = 20;
		System.out.println("执行公交车类的无参构造方法。");
	}
	Bus(int capacity)
	{
		super();
		this.capacity = capacity;
		System.out.println("执行公交车类的有参构造方法。");
	}
	public void print()
	{
		super.print();
		System.out.println("[Bus]---speed:"+super.speed+",capacity:"+capacity+",父类的capacity:"+capacity);
	}

	
	
}



package bzu.bb;

import bzu.aa.Car;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Car car = new Car();
		int speed = 0;
		while(speed<50)
		{
			speed = car.speedup();
		}
		car.print();
		while(speed>20)
		{
			speed = car.speeddown();
		}
		car.print();
		Bus bus= new Bus(25);
		bus.print();
	}

}

Lesson 3 上机练习题——继承