Skip to content

Instantly share code, notes, and snippets.

@puredanger
Created December 10, 2010 19:28
Show Gist options
  • Save puredanger/736664 to your computer and use it in GitHub Desktop.
Save puredanger/736664 to your computer and use it in GitHub Desktop.
Example of using a parameter on a constructor.
/**
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