NEFU2021-Java程序设计-实验三
实验目的
1.掌握类的继承方法及上转型对象的方法调用。
2.掌握this和super的区别及使用。
3.理解抽象类的概念及作用,掌握接口的声明,实现及接口回调。
Lab_3_7173
题目:现定义一个类体系,基类为Dog,派生类为斑点狗SpottedDog类和非斑点狗UnspottedDog类,具体要求如下:
(1)在基类中记录狗的品种breed,体重weight以及颜色color等属性,定义一个方法show()显示Dog信息;
(2)在UnspottedDog类中,调用Dog类的构造方法,重写show()方法,只显示狗的品种;
(3)在SpottedDog类中,新增表示斑点颜色的spotColor属性,定义包含四个属性的构造方法,重写show()方法;
(4)定义测试类,构造斑点狗对象,分别显示斑点狗的品种、体重、颜色和品种、颜色、斑点颜色;构造非斑点狗对象,显示狗的品种、体重、颜色信息。
(说明:构造斑点狗对象和非斑点狗对象时要分别输入,各属性值之间用空格分割,输入完后按回车键确认,输入内容参照测试数据)。
// @author: Vril_Dox
// @Date: April 10, 2021
import java.util.Scanner;
class Main{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
SpottedDog spot = new SpottedDog(reader.next(), reader.nextInt(), reader.next(), reader.next());
spot.getSuperShow();
spot.show();
UnspottedDog spot2 = new UnspottedDog(reader.next(), reader.nextInt(), reader.next());
spot2.show();
}
}
class Dog{
private int weight;
private String breed;
private String color;//以上为属性
public Dog(String breed, int weight, String color){
//父类构造方法
this.weight = weight;
this.breed = breed;
this.color = color;
}
public int getWeight(){
return this.weight;
}
public String getBreed(){
return this.breed;
}
public String getColor(){
//以上为父类get方法
return this.color;
}
public void show(){
//父类show方法,显示Dog信息
System.out.println("这是一只"+this.breed+"体重为"+this.weight+",颜色为"+this.color);
}
}
class SpottedDog extends Dog{
private String spotColor; //子类新增属性
public String getSpotcolor(){
//子类新增方法
return this.spotColor;
}
public SpottedDog(String breed, int weight, String color, String spotColor){
//子类重
super(breed, weight, color);//应该也可以使用super();代替?
this.spotColor = spotColor;
}
public void show(){
//子类重写父类show方法
System.out.println("这是一只"+getBreed()+",颜色为"+getColor()+",斑点颜色为"+getSpotcolor());
}
public void getSuperShow(){
//子类调用父类show方法
super.show();
}
}
class UnspottedDog extends Dog{
public UnspottedDog(String breed, int weight, String color){
super(breed, weight, color);