Java Objects


General J2EE: Java Objects

  1. Java Objects (2 messages)

    Have a look into the program given below.

    public class Test{
    public static void main(String argv[]){
    Test refTest = new Test();

    public void method(String aStrTest){
    System.out.println("Hello from method(String aStrTest)");

    public void method(Object aObjTest){
    System.out.println("Hello from method(Object aObjTest)");

    The code compiles fine and gives the output

    Hello from method(String aStrTest)

    At runtime.

    My doubt is why the method(String aStrTest) is called over the method(Object aObjTest) ? Both are Objects basically and why there is no ambiguity arising? Some one please explain me this.



    Threaded Messages (2)

  2. Java Objects[ Go to top ]

    Thw two methods are both applicable and accessible. The string version is the more specific match, so it is used. If you had:

    method(String s, Object o) {...}
    method(Object o, String s) {...}

    public static void main(String[] args) {
      method("foo", "bar");

    Then there would be no "most specific match", so a compile-time error would arise.

  3. Java Objects[ Go to top ]

    Most specific method is chosen, when more than one method declaration are accessible and applicable.

    The method is consider more specific than other, if any invocation handled by him could be passed to other without compile-time type error.

    Here, both
    public void method(String s) { ... }

    public void method(Object o) { ... }

    are accessible and applicable. All invocation handled by method(String a) could be passed to method(Object o) without compile-time type error, but reverse is not true.

    so method(String s) is most specific and called.