栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 多态性测试

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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);
	}
}

效果类实现:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/572861.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号