Topic
2 replies Latest Post - ‏2008-01-22T19:07:03Z by SystemAdmin
SystemAdmin
SystemAdmin
757 Posts
ACCEPTED ANSWER

Pinned topic Java quiz question, anonymous inner classes

‏2008-01-22T15:01:32Z |
For the code below the output is requested. When run it results in "Y" printed on the screen. I would have expected a compile time error (modifying the visibility of create) or the value RR to be printed.

Could anyone explain what's going one here?

Pieter
<pre>
public class Y extends R {

public static void main(String[] args) {
Y y = new Y()
{
public R create() {
System.out.println("RR");
return null;
};
};

y.create();
}

private R create() {
System.out.println("Y");
return null;
}
}

class R {
private R create() {
System.out.println("R");
return null;

}
}
<pre>

Updated on 2008-01-22T19:07:03Z at 2008-01-22T19:07:03Z by SystemAdmin
  • SystemAdmin
    SystemAdmin
    757 Posts
    ACCEPTED ANSWER

    Re: Java quiz question, anonymous inner classes

    ‏2008-01-22T16:35:46Z  in response to SystemAdmin
     Hi.

    Here is the excerpt from the "Thinking in Java" book by Bruce Eckel (chapter 7 "Polimorphism: Method call binding"]:

    "... All method binding in Java uses late binding unless a method has been declared final..."

    The private methods are final by default: you can not override them either. In other words,
    private methods are never virtual. This way, when you did:

    Y y = new Y()
    {
    public R create() {
    System.out.println("RR");
    return null;
    };
    };

    you created anonimous class with its own 'public R create()' method, that had
    nothing to do with the Y's private, non-virtual, not-overridable create() one (BTW, this is true
    for the R's create() method as well).

    As an another example: try to add some public method to the Y like

    public void virtualMethod() {
    System.out.println("Y.virtualMethod");
    }

    then add the same method to the anonymous class
    Y y = new Y()
    {
    public R create() {
    System.out.println("RR");
    return null;
    }
    public void virtualMethod() {
    System.out.println("YY.virtualMethod");
    }
    };

    and add y.virtualMethod() to main(). The output will be "YY.virtualMethod". Not news for you, I suppose.
    Then, make it private. The output will be "Y.virtualMethod".

    BTW, if you try to make R.create() protected, you will get the erorr you mentioned in your post.
    Serge.
  • SystemAdmin
    SystemAdmin
    757 Posts
    ACCEPTED ANSWER

    Re: Java quiz question, anonymous inner classes

    ‏2008-01-22T19:07:03Z  in response to SystemAdmin
    Txs,

    serge.kv learned something new today ;-)

    Pieter