简体   繁体   中英

Constructor with values from inherited abstract class, which implements an interface

I am trying to instantiate objects of type Car through a constructor and I receive the following 2 errors: "The static field Vehicle.name should be accessed in a static way" and "The final field Vehicle.name cannot be assigned" on the constructor this. variables , except numWheels.

public interface Vehicle 
{   
    String name = "";
    int maxPassengers = 0;
    int maxSpeed = 0;   
}

public abstract class LandVehicle implements Vehicle
{   
    int numWheels = 0;
    public abstract void drive();   
}

public class Car extends LandVehicle
{   
    public void soundHorn()
    {
        System.out.println("Beep, beep!");
    }

    public void drive()
    {
        System.out.println("Vroom, vroom!");
    }

    public Car(String name, int maxSpeed, int maxPassengers, int numWheels)
    {
        this.name = name;
        this.maxSpeed = maxSpeed;
        this.maxPassengers = maxPassengers;
        this.numWheels = numWheels;     
    }
}

If you define a field on an interface, it's considered to be a constant. It is public, static, and final. Static means that, instead of having a separate member variable in each object instance, there's only one for that class. And final means the value can never be changed. So in this case name can't be anything but a 0-length string, and it belongs to the interface, not to any instance implementing Vehicle.

If you want these to be instance fields, define them the way you define numWheels, putting them in a class, not in an interface. Here it looks like you mean for Vehicle to be a superclass that LandVehicle extends, so make it a class.

Interfaces describe capabilities that your object has, without providing implementations (except for default methods, never mind default methods for the time being!). The ability to add constants in an interface is a convenience, in some cases it's useful to specify constants that may get used when calling methods of that interface. Use interfaces to specify a contract that your object promises to fulfill, where it implements the interface's methods. See examples of interfaces in the JDK, such as java.lang.CharSequence and java.util.List.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM