æ¨è«ã®å ã«ãªãå¼æ°ãè¤æ°ãã£ããã©ããªãã
以ä¸ã®ãããªé¢æ°ã§ã¯ãåãã©ã¡ã¼ã¿Xã®åã¯å¼æ°ã«ãã£ã¦æ¨è«ããã¦æ±ºã¾ãã¾ãã
// åãã©ã¡ã¼ã¿ã§æå®ãããXãå¼æ°ã§è¤æ°åãåãé¢æ°ã // 渡ãããå¼æ°ã«ããXã決å®ããã static <X> X test( X a, X b ) { return a; }
ããã§ãã±ã£ã¨ã¿ãå¼æ°a,bã®åã¯åããä»£å ¥äºææ§ããªãã¨ã ãã ãã¼ãªã¼ã¨æããããå®ã¯ä»¥ä¸ã®ãããªå¼ã³åºããã§ãã¦ãã¾ãã¾ãã
test( "a", "b" ); // ããã¯ã¾ãOKã¨ã㦠test( "a", new Object() ); // ãããªã®ã test( "a", 10 ); // ãããªã®ãOK
ã©ããªã£ã¦ãããã¨ããã¨ãå
é¨ã§ã¯å¼æ°a,bã®å
±éã®è¦ªã¯ã©ã¹ãç®åºãããXã®åã¨ãã¦ä½¿ããããããã(âJava Generics FAQsãã)
ãµãã
ã§ãå¼æ°a,bã®åã«ä»£å ¥äºææ§ããªãå ´åã¨ã©ã¼ã«ãããæã¯ãâã®ããã«ããã°ããã
static <X,Y extends X> X test2( X a, Y b ) { return a; }
ãã£ã¡ã ã¨ã次ã®ãããªåä½ã«ãªãã¾ãã
test2( "a", "b" ); // OK test2( new Object(), "b" ); // OK //test2( "a", new Object() );// ã¨ã©ã¼ //test2( "a", 10 ); // ã¨ã©ã¼