题目一
1(题目编号7173)、现定义一个类体系,基类为Dog,派生类为斑点狗SpottedDog类和非斑点狗UnspottedDog类,具体要求如下:
(1)在基类中记录狗的品种breed,体重weight以及颜色color等属性,定义一个方法show()显示Dog信息;
(2)在UnspottedDog类中,调用Dog类的构造方法,重写show()方法,只显示狗的品种;
(3)在SpottedDog类中,新增表示斑点颜色的spotColor属性,定义包含四个属性的构造方法,重写show()方法;
(4)定义测试类,构造斑点狗对象,分别显示斑点狗的品种、体重、颜色和品种、颜色、斑点颜色;构造非斑点狗对象,显示狗的品种、体重、颜色信息。
(说明:构造斑点狗对象和非斑点狗对象时要分别输入,各属性值之间用空格分割,输入完后按回车键确认,输入内容参照测试数据。)
实验代码:
import java.util.*;
class Dog
{
String breed,color;
double weight;
void show(){
}
}
class SpottedDog extends Dog{
String spotColor;
SpottedDog(String breed,String color,double weight,String spotColor){
this.spotColor=spotColor;
this.breed=breed;
this.color=color;
this.weight=weight;
}
void show(){
System.out.println("这是一只"+breed+"体重为"+weight+",颜色为"+color);
System.out.println("这是一只"+breed+",颜色为"+color+",斑点颜色为"+spotColor);
}
}
class UnspottedDog extends Dog{
UnspottedDog(String breed,String color,double weight){
this.breed=breed;
this.breed=breed;
this.color=color;
}
void show(){
System.out.println("这是一只"+breed+"犬");
}
}
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
double weight;
String breed,color,spotColor;
breed=in.next();
weight=in.nextDouble();
color=in.next();
spotColor=in.next();
SpottedDog demo1=new SpottedDog(breed,color,weight,spotColor);
demo1.show();
breed=in.next();
weight=in.nextDouble();
color=in.next();
UnspottedDog demo2=new UnspottedDog(breed,color,weight);
demo2.show();
}
}
实验结果:
题目二
2(题目编号7174)、编写一个制造各种车辆的程序。包含三个类,具体要求如下:
(1)基类Vehicle,包含轮子数和汽车自身重量两个属性,一个两参数的构造方法,一个显示汽车信息的方法;
(2)小轿车类Car,增加载客数属性,重写构造方法和显示车辆信息的成员方法;
(3)卡车类Truck,增加载客数和载货量属性,重写构造方法和显示车辆信息的成员方法;
(4)主程序类,要求输入各种车辆的信息,并在控制台输出各种车辆信息。
实验代码:
import java.util.*;
class Vehicle
{
int lunzi;
double weight;
Vehicle(int lunzi,double weight){
this.lunzi=lunzi;
this.weight=weight;
}
Vehicle(){
}
void show(){
System.out.println("汽车:");
System.out.println("轮子数:"+lunzi+"个");
System.out.println("自身重量:"+weight+"吨");
}
}
class Car extends Vehicle{
int zaike;
Car(int lunzi,double weight,int zaike){
this.lunzi=lunzi;
this.weight=weight;
this.zaike=zaike;
}
void show(){
System.out.println("小轿车:");
System.out.println