generics - Java instance for comparable -
why legal create new box(); , new box<integer>();? because box comparable?
public class box<comparable> { private boolean compareto(box b) { return (this.y > b.y); } double x=0; double y=0; public static void main (string[] args) { box = new box(); box b = new box<integer>(); system.out.println(a.compareto(b)); } }
you have declared class generic type parameter. not same implementing comparable interface:
public class box<comparable> { } is same as:
public class box<t> { } which not same as:
public class box<t> implements comparable<t> { @override public int compareto(final t o) { return 0; } } because type parameter unbounded, accept type. can use integer or string:
public class box<t> { public static void main(string[] args) { box = new box(); box b = new box<>(); box c = new box<integer>(); box d = new box<string>(); } } the reason why can create new box without specifying type because of backwards compatibility. new box have raw type box<t>. bad practice , should avoided.
you can read more raw types here
if wanted enforce type parameter implements comparable, can do:
import java.awt.*; public class box<t extends comparable<t>> { public static void main(string[] args) { box = new box(); box b = new box<>(); box c = new box<integer>(); box d = new box<string>(); // 1 not work rectangle not implement comparable! box e = new box<rectangle>(); } }
Comments
Post a Comment