2016-04-22 24 views
0

喜IM试图锁定在这样一个类中的方法: 我哈瓦一个private boolean status;锁定一个布尔方法(如何在布尔方法返回任何结果还是放弃布尔方法)

status == true意味着类被锁定,status == false装置类是解锁

如果类已经被锁定,从而不能方法调用等:

protected void flip() 
    { 
     if (locked()) return; 
     face = (int) (Math.random() * 2); 
    } 

问题是:

我得到了与布尔方法的问题,考虑一下:

protected boolean isHeads() 
    { 
     //if(!locked()) return false or true; 
     //if i write upper command then its true or false like the bottom command and its unclear that this false or true is for which of them 
     //if(!locked()) 
    //if i write this command then i have to write another return and its the same problem too; 
     return (face == HEADS); 

    } 

注:我有一个接口,所以我不能改变对锁定)的方法(和锁等;

+0

你真的需要阻止不改变对象状态的方法吗?如果是这样,抛出新的RuntimeException();'。这将完全打破所有的调用代码,但按照你所要求的方式无论如何都会这样做。 – Siguza

+0

是的,我需要这个,你能给我示例代码plz @Siguza –

+1

你可以改变你的方法返回一个布尔对象,那么你可以返回null,如果你不想返回true或false。 或者,如果您使用的是Java8,则可以返回一个可选。 – mdewit

回答

3

正确的设计,这类节目是抛出一个异常,所以代码应该是这样的:

protected boolean isHeads() throws ObjectIsLockedException 
{ 
    if(locked()) throw new ObjectIsLockedException(); 
    return (face == HEADS); 
} 

注意ObjectIsLockedExpception不是Java异常:你必须将其声明为一个在你的代码中的类。

0

你不能从布尔方法中不返回任何东西。它必须是真的或假的。返回一个int或枚举或使函数等待。