Results 1 to 3 of 3
  1. #1
    Jonah Bron's Avatar
    Jonah Bron is offline Member
    Join Date
    Sep 2010
    Location
    California
    Posts
    26
    Rep Power
    0

    Default Create Different update() Methods for Observer

    Hello, world!

    I have an Observer/Observable set up, and I would like to accept two different object types from the observable. I tried just making the two update functions:

    Java Code:
    public void update(Observable observable, Integer message) {
        // do something with message
    }
    public void update(Observable observable, String message) {
        // do something with message
    }
    public void update(Observable observable, Object message) {}
    But they weren't called, instead the main update(Object) method was called. How can I get it to call my other update()s instead, or is there another way to accept multiple types (without typecasting; I need to know what type of object it is).

    Thanks!

  2. #2
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    5

    Default

    could you just bake the type casting into the update(Object) one?

    Java Code:
    public void update(Observable observable, Object message) {
      if (message instanceof Integer) {
        update(observable, (Integer) message);
      }
      else if (message instanceof String) {
        update(observable, (String) message);
      }
      else {
        // do something with object
      }
    }
    
    public void update(Observable observable, Integer message) {
        // do something with message
    }
    public void update(Observable observable, String message) {
        // do something with message
    }

  3. #3
    Jonah Bron's Avatar
    Jonah Bron is offline Member
    Join Date
    Sep 2010
    Location
    California
    Posts
    26
    Rep Power
    0

    Default

    Ah, that works perfectly, thanks. I didn't think that would work... I figured it would say return false and say it was an Object.

    For future reference, I tried without the if (just calling the the other update directly), but it didn't work; apparently the typecast is necessary.

Similar Threads

  1. Pattern Observer
    By brontolo in forum Advanced Java
    Replies: 6
    Last Post: 09-02-2010, 02:40 PM
  2. Static Builder and Create Methods for simple class
    By Pilot Ace in forum New To Java
    Replies: 3
    Last Post: 08-30-2009, 10:18 AM
  3. need to create two methods
    By alims52 in forum New To Java
    Replies: 2
    Last Post: 10-26-2008, 12:35 PM
  4. How to create object dinamically and call methods.
    By Gelembjuk in forum New To Java
    Replies: 8
    Last Post: 10-26-2008, 09:28 AM

Tags for this Thread

Posting Permissions

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