2014-06-17 68 views
0
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; 
    } 
} 

我得到「試圖分配更弱的特權」。實施接口不工作

+5

製作'sayHello'在''HelloImpl' public'。 – rgettman

+1

你能告訴我爲什麼嗎? –

+0

使用覆蓋其他方法的'@ override'註釋前面的方法也是一個好主意。 – vandale

回答

7

interface默認情況下,所有成員都是public

您不能實現(或覆蓋)一個方法並分配較弱的特權,因爲這不允許多態。

您必須製作sayHello()public

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

    public String sayHello() { 
     return message; 
    } 
} 

此外,內部常量應該是private final

+0

那麼,我需要明確地說我的方法是公開的? –

+0

@GeorgeIrimiciuc是的,爲什麼會這樣呢? –