1
public class TestImpl {
    public static void main(String[] args) {
        HelloImpl h1 = new HelloImpl(), h2 = h1;
        h1.message = "holla";
        System.out.println(h2.sayHello());
    }
}

interface Hello {
    String sayHello();
}

class HelloImpl implements Hello {
    static String message = "Hello";

    String sayHello() {
        return message;
    }
}

I get "attempting to assign weaker privilegies."

George Irimiciuc
  • 4,573
  • 8
  • 44
  • 88
  • 5
    Make `sayHello` `public` in `HelloImpl`. – rgettman Jun 17 '14 at 21:01
  • 1
    Can you tell me why, please? – George Irimiciuc Jun 17 '14 at 21:02
  • It is also a good idea to use the `@override` annotation preceding methods that override other methods. – vandale Jun 17 '14 at 21:03
  • Take a look at [Controlling Access to Members of a Class](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) – MadProgrammer Jun 17 '14 at 21:04
  • If you are interested in why in most cases methods declared in interface don't have `public` modifier take a look [here](http://stackoverflow.com/questions/161633/should-methods-in-a-java-interface-be-declared-with-or-without-a-public-access-m). – Pshemo Jun 17 '14 at 21:06

2 Answers2

7

In an interface all members are public by default.

You cannot implement (or override) a method and assign weaker privileges as this would not allow polymorphism.

You must make sayHello() public.

class HelloImpl implements Hello {
    private static final String message = "Hello";

    public String sayHello() {
        return message;
    }
}

Also, internal constants should be private final

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
1

"All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier." from http://docs.oracle.com/javase/tutorial/java/IandI/interfaceDef.html

Your interface's method is implicitly public but the implementing class method is not

matt
  • 115
  • 5