Java riddle: static binding

78 views Asked by At

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;
    }

}
1

There are 1 answers

0
Aditya Singh On
  1. bar() defined in class B is called ofcourse. If you believe that method from interface A is called, I must tell you that methods from an interface are never CALLED. As Interfaces have only method declarations(unless it's a default method) that an implementing non-abstract class has to define. And the line return this.foo is executed.

  2. return statement from the main method ends the program. It returns to the JVM, which in turn returns to the OS.