java 多态性测试

java 多态性测试,第1张

java 多态性测试

(1)编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数wheels和车重weight。

(2)小车类Car是Vehicle的子类,其中包含的属性有载人数loader。

(3)卡车类Truck是Car类的子类,其中包含的属性有载重量payload。

(4)每个类都有构造方法和输出相关数据的方法show。

(5)编写测试类进行多态性测试。

以下代码用两种方式实现

代码类实现方式一:

public class VehicleTest {
	public static void showInfo(Vehicle v) {
		v.show();
	}
	public static void main(String[] args) {
		Car c = new Car(4, 100, 20);
		Truck t = new Truck(14, 1100, 120, 1200);
		System.out.println("---------------输出Car的信息---------------");
		showInfo(c);
		System.out.println("---------------输出Truck的信息---------------");
		showInfo(t);
	}

}
class Vehicle {
	int wheels;
	double weight;
	public Vehicle(int wheels, double weight) {
		this.wheels = wheels;
		this.weight = weight;
	}
	public void show() {
		System.out.println("车轮数:" + wheels);
		System.out.println("车重:" + weight);
	}
}
class Car extends Vehicle {
	int loader;

	public Car(int wheels, double weight, int loader) {
		super(wheels, weight);
		this.loader = loader;
	}
	public void show() {
		super.show();
		System.out.println("载人数:" + loader);
	}
}
class Truck extends Car {
	double payload;

	public Truck(int wheels, double weight, int loader, double payload) {
		super(wheels, weight, loader);
		this.payload = payload;
	}
	public void show() {
		super.show();
		System.out.println("载重量:" + payload);
	}
}

代码类实现方式二:

public class VehicleTest1 {
	public static void main(String[] args) {
		Vehicle c = new Car(4, 100, 20);
		Vehicle t = new Truck(14, 1100, 120, 1200);
		System.out.println("---------------输出Car的信息---------------");
		c.show();
		
		System.out.println("---------------输出Truck的信息---------------");
		t.show();
	}

}
class Vehicle {
	int wheels;
	double weight;
	public Vehicle(int wheels, double weight) {
		this.wheels = wheels;
		this.weight = weight;
	}
	public void show() {
		System.out.println("车轮数:" + wheels);
		System.out.println("车重:" + weight);
	}
}
class Car extends Vehicle {
	int loader;

	public Car(int wheels, double weight, int loader) {
		super(wheels, weight);
		this.loader = loader;
	}
	public void show() {
		super.show();
		System.out.println("载人数:" + loader);
	}
}
class Truck extends Car {
	double payload;

	public Truck(int wheels, double weight, int loader, double payload) {
		super(wheels, weight, loader);
		this.payload = payload;
	}
	public void show() {
		super.show();
		System.out.println("载重量:" + payload);
	}
}

效果类实现:

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5564100.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存