why is the equal method of Object class is getting called?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ankitc7
    New Member
    • Jun 2010
    • 3

    why is the equal method of Object class is getting called?

    Code:
    final class Item {
    Integer size;
    Item(Integer size) { this.size = size; }
    public boolean equals(Item item2) {
    if (this == item2) return true;
    return this.size.equals(item2.size);
    }
    }
    public class SkepticRide {
    public static void main(String[] args) {
    Item itemA = new Item(10);
    Item itemB = new Item(10);
    Object itemC = itemA;
    System.out.println("|" + itemA.equals(itemB) +
    "|" + itemC.equals(itemB) + "|");
    }
    }
    Last edited by Niheel; Jun 1 '10, 08:58 AM. Reason: Use code tags to post questions
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    itemC is declared to be an Object, not an Item. If you want it to call the Item's equal method, you need to explicitly cast it as an Item:
    ((Item)(itemC)) .equals(itemB);

    Comment

    • ankitc7
      New Member
      • Jun 2010
      • 3

      #3
      But doesn't the run time polymorphism apply here ??

      A super class reference variable(Object 's) item c is pointing to a sub class object(Item A)..so the overridden method should be called..like in tis code:

      Code:
      class superclass {
      public void func() {
      System.out.println("superclass");
      }
      }
      
      class subclass extends superclass{
      public void func() {
      System.out.println("subclass");
      }
      }
      
      public class SkepticRide {
      public static void main(String[] args) {
      superclass sup=new subclass();
      sup.func();
      }
      }
      
      here subclass func wud be called
      Last edited by Niheel; Jun 1 '10, 02:51 PM. Reason: ankit, use code tags to display code

      Comment

      • jkmyoung
        Recognized Expert Top Contributor
        • Mar 2006
        • 2057

        #4
        I'm not 100% sure but:
        It has to do with the fact that your function uses Item as opposed to Object.
        public boolean equals(Item item2)

        Object does not have a public boolean equals(Item item2)
        method, so it does not know to call Item's .equals(Item) function.

        If you rewrote your function as
        public boolean equals (Object item2)
        then it would probably call the correct function.

        Comment

        • ankitc7
          New Member
          • Jun 2010
          • 3

          #5
          yes you are correct...this has nothing to do with polymorphism... thanks a lot!!

          Comment

          Working...