I'm given Class C
and interface A
and I'm not allowed to do any changes in them. I should write class B
so that the code will always output success!
There is two things that I don't understand in the code of class C
inside the for loop.
1) I don't understand which bar method is called.
2) when return is reached where does it return to?
Should I change the implementation of B
in order to get it to work?
public interface A {
public String bar();
}
public class C extends B {
public int foo = 100;
public C(String s) {
super(s);
}
@Override
public void barbar() {
foo++;
}
public static void main(String[] args) {
String input = args[0];
StringBuilder builder = new StringBuilder(input);
C c = new C(input); //c=args[0]
B b = c; //b=args[0]
A a = b; //a=args[0]
for (int i = 0; i < args.length; i++) {
if (!builder.toString().equals(a.bar())) { //which bar is called?
return; //where does it return to? does it exist the for loop?
}
builder.append(input);
c.foo++;
}
if (c.foo - 99 == b.foo.length() / input.length()) {
System.out.println("success!");
}
}
}
public class B implements A {
public String foo;
public B(String s) {
this.foo=s;
}
public void barbar() {
// TODO Auto-generated method stub
}
@Override
public String bar() {
return this.foo;
}
}
bar()
defined inclass B
is called ofcourse. If you believe that method frominterface A
is called, I must tell you that methods from an interface are never CALLED. As Interfaces have only method declarations(unless it's adefault
method) that an implementing non-abstract class has to define. And the linereturn this.foo
is executed.return
statement from themain
method ends the program. It returns to the JVM, which in turn returns to the OS.