Results 1 to 6 of 6
  1. #1
    Somelauw is offline Member
    Join Date
    Nov 2009
    Posts
    10
    Rep Power
    0

    Default Dynamic types for a variable.

    Is it possible to pass a class as a variable to a function? (or any workaround)

    I want something like:

    Java Code:
    static <type> function(<type> a) {
         a.method();
    }
    and then use it as:
    Java Code:
         function(Subclass a);
    Such that java replaces <type> by Subclass in the function.

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

    Default

    Usually interfaces are used for such indirections. Instead of passing "functions" (methods in Java), you pass an object that implements a particular interface. If you've ever done Swing coding, then you're familiar with this concept when using ActionListener objects.

    I suppose that Java 7 may address this with closures, but I'm not sure on that point (nor that it even needs "addressing").

  3. #3
    Somelauw is offline Member
    Join Date
    Nov 2009
    Posts
    10
    Rep Power
    0

    Default

    Does that mean that the following works?

    Java Code:
    public interface Inter {
         public static void foe();
    }
    Java Code:
    class Thing extends Inter {
         public static void foe() {
              System.out.println("hello world!");
         }
    }
    Java Code:
    public static void main() {
         bar(new Thing()); //Will this print "Hello World"?
    }
    
    public static void bar(Inter thing) {
        thing.foe();
    }

  4. #4
    dinosoep is offline Senior Member
    Join Date
    Nov 2009
    Posts
    150
    Rep Power
    6

    Default

    yes it will.
    but without that interface it still would work :p

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,771
    Blog Entries
    7
    Rep Power
    21

    Default

    And to complete the confusion have a look at Generics.

    kind regards,

    Jos

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

Similar Threads

  1. again -.- unsigned types
    By prich in forum Networking
    Replies: 1
    Last Post: 10-17-2009, 06:53 PM
  2. generic types
    By jon80 in forum New To Java
    Replies: 6
    Last Post: 06-12-2009, 11:29 PM
  3. Collection Types
    By DavidG24 in forum New To Java
    Replies: 2
    Last Post: 04-18-2009, 06:03 PM
  4. WHy does it say imcompatable types?
    By PeterFeng in forum New To Java
    Replies: 3
    Last Post: 01-14-2009, 06:54 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
  •