Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Fundamental OO question (in Java)

Options
  • 16-07-2005 12:57pm
    #1
    Posts: 0


    Hey all,

    I know this is basic, but I just want to get it clear in my head, as the principle is used quite widely in Java, that of polymorphism.

    I hope that I have the right term there, but here goes:

    The code snippet:

    List myList = new ArrayList();

    is valid.

    My understanding of this is that, as ArrayList is a subclass of List, then it will assign the instance of ArrayList to the reference variable myList of type List.
    But am I right in that only the methods that are in type List will be accessible and that you cannot refer to the methods in the ArrayList type unless you cast later on?

    Is this polymorphism or something else in OO terminology?

    I think i have this in my head, it would just be cool for someone to set it straight, thanks for any help/info.


Comments

  • Registered Users Posts: 1,184 ✭✭✭causal


    MoonHawk wrote:
    My understanding of this is that, as ArrayList is a subclass of List,
    java.util.List is an interface - java.util.ArrayList is a class that implements the List interface
    So ArrayList is not a subclass of List. The ArrayList class hierarchy is as follows:
    java.lang.Object > java.util.AbstractCollection > java.util.AbstractList > java.util.ArrayList

    Polymorphism literally means 'many forms'.
    In java there are 2 types of polymorphism - overloading, overriding.

    Very simply*:
    An example of overloading is where more than one method in a class share the same name - but have different input parameter lists.
    An example of overriding is where one or more methods in a subclass share the same name as methods in their immediate superclass - but have different input parameter lists. (this is what you were trying to show with your example)

    *There are many rules governing acceptable return types, access modifiers, parameter lists, exceptions etc. of overloaded and overriden methods.
    Variables can also be overloaded and overridden.

    hth,
    causal


  • Posts: 0 [Deleted User]


    nice one, thanks for the feedback.


Advertisement