【问题标题】:Solving a java riddle解决一个java谜语
【发布时间】:2015-06-08 15:59:55
【问题描述】:

我得到了 A 和 C 类,我应该编写 B 类,这使得 C 类中的 main 输出始终为 successful! 。 正弦有一个随机布尔变量,只有当它为假时我才会得到一个好的结果,当它为真时我没有得到输出。 我不允许在 A 或 C 类中进行任何更改。

我知道问题出在C 类中的第三个if,但是我可以在B 类中进行哪些更改以防止进入这个if?

    public class A {

    public String foo(String s) {
        return s;
    }
}

    public class B extends A {


    public A getA(boolean flag){
        A a = new A();
        if (flag){

            return(a);
        }
        else{
            return (a);
        }

    }

}


    package sw1.riddles.second;

import java.util.Random;

public class C {

    public static void main(String[] args) {
        String input = args[0];
        B b = new B();
        Random random = new Random();
        boolean randomBool = random.nextBoolean();
        A a = b.getA(randomBool);

        if (randomBool) {
            if (!input.equals(a.foo(input))) {
                return;
            }
        } else {
            if (!(input+input).equals(a.foo(input))) {
                return;
            }
        }
        System.out.println("success!");
    }
}

【问题讨论】:

  • A 不是最终的,因此您可以使用 B.getA 中的匿名子类覆盖它,这取决于您的标志。这里的目的是什么?看起来很奇怪的学校作业。
  • 不需要匿名子类。只需覆盖 B 中的 foo() 并在 flag 为 false 时返回 this。
  • 您不能联系return。所以 a.foo(input) 必须返回 input (randomBool) 或 input+input (!randomBool)。所以b.getA(randomBool) 必须返回不同的东西。

标签: java class oop if-statement


【解决方案1】:

B类应该如下:

public class B extends A{
    public String foo(String s){
        return s+s;
    }

    public A getA(boolean flag){
        if (flag){
            A a = new A();
            return(a);
        }
        else{
            B b = new B();
            return (b);
        }
    }
}

【讨论】:

    【解决方案2】:

    也许解决办法:

    public class B extends A {
    
    
        public A getA(boolean flag){
            if (flag){ //true -> usual A with foo == input
                return new A(); //or this
            }
            //false-> custom A with foo == input + input
            return new A(){
                @Override
                public String foo(String s) {
                    return s+s;
                }
            };
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 2020-05-14
      相关资源
      最近更新 更多