如何用Java中的子类方法覆盖父类的方法?

-1 java overriding

我有一个任务:

修改类汽车,使其覆盖有它自己版本的方法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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 12

setCapacity()Car类方法不会覆盖类的setCapacity(int newCapacity)方法Vehicle.

为了覆盖基类的方法,子类方法必须具有相同的签名.

更改

public void setCapacity()
{
   System.out.println("Cannot change capacity of a car");
}
Run Code Online (Sandbox Code Playgroud)

@Override
public void setCapacity(int newCapacity)
{
   System.out.println("Cannot change capacity of a car");
}
Run Code Online (Sandbox Code Playgroud)

请注意,添加@Override属性是可选的,但它会告诉编译器您要覆盖基类方法(或实现接口方法),如果您错误地声明了重写方法,这将导致有用的编译错误.