Results 1 to 6 of 6
Thread: Dynamic types for a variable.
- 11-26-2009, 03:55 PM #1
Member
- Join Date
- Nov 2009
- Posts
- 10
- Rep Power
- 0
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:
and then use it as:Java Code:static <type> function(<type> a) { a.method(); }
Such that java replaces <type> by Subclass in the function.Java Code:function(Subclass a);
-
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").
- 11-26-2009, 09:10 PM #3
Member
- Join Date
- Nov 2009
- Posts
- 10
- Rep Power
- 0
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(); }
- 11-26-2009, 09:12 PM #4
Senior Member
- Join Date
- Nov 2009
- Posts
- 150
- Rep Power
- 4
yes it will.
but without that interface it still would work :p
- 11-26-2009, 09:15 PM #5
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,427
- Blog Entries
- 7
- Rep Power
- 17
And to complete the confusion have a look at Generics.
kind regards,
Jos
- 11-27-2009, 10:38 AM #6
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Similar Threads
-
again -.- unsigned types
By prich in forum NetworkingReplies: 1Last Post: 10-17-2009, 05:53 PM -
generic types
By jon80 in forum New To JavaReplies: 6Last Post: 06-12-2009, 10:29 PM -
Collection Types
By DavidG24 in forum New To JavaReplies: 2Last Post: 04-18-2009, 05:03 PM -
WHy does it say imcompatable types?
By PeterFeng in forum New To JavaReplies: 3Last Post: 01-14-2009, 05:54 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks