Java继承与多态

124 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

继承与多态

包的导入

package 包名
import 包名.类名

继承

继承是面向对象程序设计的一个重要特征,Java都是单继承,子类通过父类继承父类构造方法。

代码示例:

public class Vehicles {
	protected String brand;
 	protected String color;
 	public Vehicles(String brand, String color) {
	super();
	this.brand = brand;
	this.color = color;
  }
    public void showInfo(){
    	System.out.println("品牌:"+brand+"\t"+"颜色:"+color);
    }
    public void run() {
		System.out.println("我"+brand+"正在行驶");
	}
}
public class Car extends Vehicles{
    protected int seat;
	public Car(String brand, String color,int seat) {
		super(brand, color);
		this.seat = seat;
	}
    public void showCar(){
    	System.out.println("我是一辆:"+brand+"\t"+"我的颜色:"+color+"\t"+"我有:"+seat+"个座位");
    }
}
public class Truck extends Vehicles {
    protected double load;
	public Truck(String brand, String color,Double load) {
		super(brand, color);
		this.load = load;
	}
    public void showTruck(){
    	System.out.println("我是一辆:"+brand+"\t"+"我的颜色:"+color+"\t"+"我的载重:"+load+"吨的材料");
    }
}

车类和卡车类继承了父类车辆类