Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding methods in Interface java

Tags:

java

netbeans

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);
    }
}
like image 618
Moawiya Avatar asked Dec 20 '22 12:12

Moawiya


2 Answers

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.

like image 58
Xabster Avatar answered Dec 22 '22 02:12

Xabster


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.

like image 37
Eutherpy Avatar answered Dec 22 '22 03:12

Eutherpy