Reputation: 157
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);
}
}
Upvotes: 4
Views: 386
Reputation: 1187
lets suppose you have a interface Printable,which contains a method print().
interface Printable{
int MIN=5;
void print();
}
now because the method is declared inside interface , compiler implicitly adds public abstract before the method. like this :- interface for compiler
now as the method is been declared public , so now when you extend the method you have to add public before the method.
I think this might help you.
Upvotes: 0
Reputation: 4581
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.
Upvotes: 3
Reputation: 3720
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.
Upvotes: 8