[英]How to override a parent class's method with a child class's method in Java?
我的任务是:
修改Car类,使其使用其自身的版本覆盖setCapacity方法,该方法将输出消息“无法更改汽车的容量”并且不更改引擎容量。
我试图解决以下代码中的任务,但它继续使用Vehicle
类的setCapacity
方法而不是Car
方法。
class Vehicle // base class
{
int capacity;
String make;
Vehicle(int theCapacity, String theMake)
{
capacity = theCapacity;
make = theMake;
}
void print()
{
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
public void setCapacity(int newCapacity)
{
capacity = newCapacity;
System.out.println("New capacity = " + capacity);
}
}
class Car extends Vehicle
{
String type, model;
Car(int theCapacity, String theMake, String theType, String theModel)
{
super(theCapacity, theMake);
type = theType;
model = theModel;
}
public void print()
{
super.print();
System.out.println(" type = " + type);
System.out.println(" model = " + model);
}
public void setCapacity()
{
System.out.println("Cannot change capacity of a car");
}
}
class Task3
{
public static void main(String[] args)
{
Car car1 = new Car(1200,"Holden","sedan","Barina");
Vehicle v1 = new Vehicle(1500,"Mazda");
v1.setCapacity(1600);
v1.print();
car1.setCapacity(1600);
car1.print();
}
}
Car
类的setCapacity()
方法不会覆盖Vehicle
类的setCapacity(int newCapacity)
方法。
为了覆盖基类的方法,子类方法必须具有相同的签名。
更改
public void setCapacity()
{
System.out.println("Cannot change capacity of a car");
}
至
@Override
public void setCapacity(int newCapacity)
{
System.out.println("Cannot change capacity of a car");
}
请注意,添加@Override
属性是可选的,但它会告诉编译器您打算重写基类方法(或实现接口方法),如果您错误地声明了重写方法,则会导致有用的编译错误。
问题可能是名称为“ setCapacity”的Car类的方法未覆盖具有相同名称的父类Vehicle的方法。因为它没有参数,但其父类中有一个参数。 希望可以帮到您!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.