Created
December 10, 2010 19:28
-
-
Save puredanger/736664 to your computer and use it in GitHub Desktop.
Example of using a parameter on a constructor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Example of using a parameter on a constructor. Parameters on methods are used to | |
describe either type relationships between arguments to the method or between the | |
argument and the return type (more common but not possible in a constructor). Here | |
I use the type X to specify that the two args are of the same type. | |
When calling it, specifying the type is optional as it will automatically be | |
inferred. In cases where the incorrect type is inferred (wrong place in shared | |
hierarchy), you can specify it. If there is no common type, you'll get an error | |
at compile time. | |
*/ | |
public class TwoOfAType { | |
private Object[] stuff = new Object[2]; | |
public <X> TwoOfAType(X a1, X a2) { | |
stuff = new Object[] { a1, a2 }; | |
} | |
public String toString() { | |
return stuff[0] + " " + stuff[1]; | |
} | |
public static void main(String arg[]) { | |
TwoOfAType t = new <String> TwoOfAType("a", "b"); | |
System.out.println(t);public class TwoOfAType { | |
private Object[] stuff = new Object[2]; | |
public <X> TwoOfAType(X a1, X a2) { | |
stuff = new Object[] { a1, a2 }; | |
} | |
public String toString() { | |
return stuff[0] + " " + stuff[1]; | |
} | |
public static void main(String arg[]) { | |
TwoOfAType t = new <Number> TwoOfAType(Integer.valueOf(1), Double.valueOf(2.0)); | |
System.out.println(t); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment