Results 1 to 4 of 4
  1. #1
    desmo is offline Member
    Join Date
    Oct 2010
    Posts
    2
    Rep Power
    0

    Default Pass multiple object types to one function

    Hi all,

    I have a requirement where I have to pass a number of objects to a function and process them by calling a common method, getComments().

    I would like to pass any of a number of types of objects, call the getComments() method, parse, then update the original object.

    You can think of something similar like passing objects like:

    cars, trucks, motorcycles and calling a method like getCurrentValue() (or something similar).

    Is this possible?

    Thanks much in advance!

    M

  2. #2
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    If you have a class Car, a class Truck, and a class Motorcycle, they could all extend a Vehicle class which contains the methods you want. Each of the subclasses can then override those methods and the Vehicle object can be safely passed to the method.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,453
    Rep Power
    20

    Default

    Or you could have all the classes implement an interface (for discussion's sake let's call it Commentable) and the method (not function, Java doesn't have functions) wold accept a Commentable argument.


    call the getComments() method, parse, then update the original object.
    A getComments method shouldn't update anything. By convention, getXxx methods are accessors. If the purpose of the method is to update the comments, it should be named updateComments. If simply to set a new value for the comments field, then setComments.

    And if the method obtains all input via its parameter(s) and doesn't depend on the state of the current object, it should probably be static.

    db

    edit Oh, I think I misread that. The method that does the updating isn't getComments.
    Last edited by DarrylBurke; 10-08-2010 at 05:30 AM.

  4. #4
    desmo is offline Member
    Join Date
    Oct 2010
    Posts
    2
    Rep Power
    0

Similar Threads

  1. Sorting/Searching Objects with multiple types.
    By gcampton in forum New To Java
    Replies: 20
    Last Post: 10-22-2009, 12:58 AM
  2. Replies: 1
    Last Post: 03-04-2009, 07:14 PM
  3. Multiple types in Vector - type checking
    By Excession in forum Advanced Java
    Replies: 5
    Last Post: 07-13-2008, 08:06 PM
  4. Hastable - Multiple Types
    By sopna sajith in forum Advanced Java
    Replies: 3
    Last Post: 06-29-2008, 05:40 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •