Results 1 to 3 of 3
  1. #1
    alinaqvi90 is offline Member
    Join Date
    May 2010
    Posts
    32
    Rep Power
    0

    Question passing type info to a method during run time

    Hi All

    I have a situation where I have a number of classes inheriting a single parent.

    e.g.

    public class ChildA extends parentClass{...}

    public class ChildB extends parentClass{...}

    public class ChildC extends parentClass{...}



    And I have my own class:

    public class myClass()
    {
    public myMethod(parentClass obj)
    {
    /*The reason I am passing an obj here is to pass in the type info
    to do some thing like: */

    if(obj instanceof ChildA)
    {
    //do some thing non polymorphic.
    }

    else if(obj instanceof ChildB)
    {
    //do some thing non polymorphic.
    }

    else if(obj instanceof ChildC)
    {
    //do some thing non polymorphic.
    }


    }

    }


    So basically I am passing an object to myMethod() just as type info. Is there any way to avoid this and have a better design ??

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,874
    Rep Power
    8

    Default

    Your example is too generic to really help you out, but you might want to look at: Class (Java Platform SE 6)

    But yeah, there's almost definitely a better way to do what you want, design-wise.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Are you familiar with design patterns? If not, you might want to learn about them as they can often help you avoid the non-OOP behavior you are describing above. Possible patterns that could work here include the Command Pattern or the Mediator Pattern.

    Luck!

Similar Threads

  1. Replies: 4
    Last Post: 03-12-2010, 05:57 PM
  2. need info on running thread during a particular time interval alone
    By karthikeyan_raju in forum Threads and Synchronization
    Replies: 2
    Last Post: 10-06-2009, 02:40 AM
  3. Replies: 0
    Last Post: 03-08-2009, 01:52 PM
  4. passing info between server/client problem
    By DarkBlaze in forum New To Java
    Replies: 13
    Last Post: 07-24-2008, 03:14 AM
  5. passing an enum type as a parameter ??!
    By SCS17 in forum New To Java
    Replies: 11
    Last Post: 07-13-2008, 01:44 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
  •