Results 1 to 4 of 4

Thread: return subtype

  1. #1
    TheSheepeh is offline Member
    Join Date
    Mar 2011
    Posts
    5
    Rep Power
    0

    Default return subtype

    Think I got the title right there.

    Basically I have a superclass called SpaceObject. I have another superclass below that of SpaceShip(and then different spaceships below this)

    I have an arraylist of SpaceObjects. How can I know if an element in my arraylist of SpaceObjects is a SpaceShip?

    public SpaceObject getType(){

    return this;
    }

    I imagine something like this would work, but can't work out how I would do an if statement to check if its type SpaceShip (and what type of spaceship would be handy)

    Thanks!

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default

    If I understand correctly, instanceof might be what you are looking for
    Java Code:
    if ( this instanceof SpaceShip ){
    ///I'm a spaceship
    }
    Note that calling something like
    Java Code:
    if ( myClass instanceof SpaceObject){//true for all child classes of SpaceObject
    
    }
    will evaluate to true for all child classes as well. There are other ways to go about this, for example defining the type in the constructors.

  3. #3
    TheSheepeh is offline Member
    Join Date
    Mar 2011
    Posts
    5
    Rep Power
    0

    Default

    Yup

    That's done the trick, thx alot

  4. #4
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    If you are done please mark your thread solved with the thread tools. Glad you figured it out.

Similar Threads

  1. return array
    By rfviki in forum New To Java
    Replies: 2
    Last Post: 11-03-2010, 01:05 PM
  2. If Statement return
    By ricardo5222 in forum New To Java
    Replies: 4
    Last Post: 11-01-2010, 11:43 AM
  3. Using int/int, 7/5 would return 1
    By zoe in forum New To Java
    Replies: 2
    Last Post: 12-02-2008, 11:25 AM
  4. about 'return'.
    By helloworld in forum New To Java
    Replies: 9
    Last Post: 11-28-2008, 04:08 AM
  5. if..else..return
    By mqdias in forum New To Java
    Replies: 1
    Last Post: 08-10-2007, 04:20 PM

Posting Permissions

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