Search code examples
javainterfacescopeaccess-specifier

Why should I declare implemented interface methods as "public"?


interface Rideable {
    String getGait();
}

public class Camel implements Rideable {
    int weight = 2;

    String getGait() {
        return " mph, lope";
    }

    void go(int speed) {++speed;
        weight++;
        int walkrate = speed * weight;
        System.out.print(walkrate + getGait());
    }

    public static void main(String[] args) {
        new Camel().go(8);
    }
}

Upon compiling the above code I've got a compilation error, related to access modifier of getGait() method. Please explain, why should I declare getGait() with public access modifier?


Solution

  • getGait() of Camel implements a method of the Rideable interface. All interface methods are public by default (even if you don't specify it explicitly in the interface definition), so all implementing methods must be public too, since you can't reduce the visibility of the interface method.