I wrote an Interface in Java. after that I tried to implement it by overriding as shown in the code. but I get error that I have to add public before the method.
why I have to add public ? why without public it does not work ?
as the Net-Beans says : " attempting to assign weaker access privileges; was public "
the code :
package tryinginterface;
interface Bicycle {
// wheel revolutions per minute
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
class ACMEBicycle implements Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
@Override
void changeCadence(int newValue) {
cadence = newValue;
}
@Override
void changeGear(int newValue) {
gear = newValue;
}
@Override
void speedUp(int increment) {
speed = speed + increment;
}
@Override
void applyBrakes(int decrement) {
speed = speed - decrement;
}
@Override
void printStates() {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
All methods in interfaces are public.
All methods in a class without a visibility modifier are package-private.
You cannot reduce the visibility of the public methods to package-private because it violates the interface.
Because in an interface, all methods are by default public, and in a class, the default visibility of methods is "friend" - seen in the same package.
You can't narrow down the visibility when implementing a method, that's the rule.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With