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

时间:2018-05-24 07:30:26

标签: java method-overriding

我有一个任务:

  

修改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();
    }
}

2 个答案:

答案 0 :(得分:12)

setCapacity()课程的Car方法不会覆盖setCapacity(int newCapacity)课程的Vehicle方法。

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

更改

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属性是可选的,但它会告诉编译器您要覆盖基类方法(或实现接口方法),这将导致有用的编译错误,如果您宣布重写方法不正确。

答案 1 :(得分:0)

问题可能是Car的类方法名称为" setCapacity",它不会覆盖其父类Vehicle的同名方法。因为它没有一个参数,但它的父类中有一个参数。 希望可以帮到你!