-2

I am making a Bicycle interface acting as a blueprint for all types of bikes.

I have multiple classes that implements the Bicycle interface, classes such as BMX, MountainBike, RoadBike, MotorBike...etc.

Now, I understand that interfaces are one way to force each of the classes that implement it to have multiple things like String seats, double wheelDimensions, double topSpeed, int gears... These are some of the things I want to force all the classes to have when the Bicycle interface is implemented.

Is interface the right approach or is it abstraction? Because when I try to declare a String (for example: String seat) in the interface, it says it must be instantiated. I want the classes to instantiate the seat and not the interface. Because each class will have different type of seats.

I was under the assumption that interfaces are a way to force classes that implement it with the things the interface wants?

tarrzaann
  • 1
  • 2
  • 2
    https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html – QBrute Mar 25 '23 at 18:59
  • Before posting here, always read [Wikipedia](https://en.wikipedia.org/wiki/Interface_(Java)), and study Oracle's free-of-cost tutorial on Java. See the [tutorial on interfaces](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html). To quote: *an interface is a group of related methods with empty bodies*. So no member fields in an interface in Java. Your attempt to declare a String (for example: String seat) is nonsensical in Java. You may want to learn about *abstract class* in Java. – Basil Bourque Mar 26 '23 at 00:30

1 Answers1

-1

If you want to declare a state for each Bicycle (like 'seats', wheelDimensions, topSpeed, gears etc) - abstract class is the way to go, as it allows to declare those fields.

If you want to declare what actions are allowed by Bicycle or onto Bicycle (like 'startRide', 'getSpeed', 'jump' etc) - interface is the way to go, as it will just specify what is expected from Bicycle in general, without going into details.

One downside with using abstract class for such approach - that if for some reason one of bikes would not have some property of abstract class (for example - some bike has no seats at all) - it will still have a seat field (even it is equal to 0).

However, both approaches (interface & abstract class) could be used or even combined to achieve needed functionality

Daniel
  • 630
  • 5
  • 9