Πϥ΄Ͳ࠷దԽ͞Εͳ͍ϚγϯɾίʔυΛੜ͠·͢ɻ ͜ͷίϯύΠϥΛ༻͢Δͱɺਝʹىಈ͠·͢ɻ ·ͨɺ͜ͷίϯύΠϥͰɺগͳ͍ϝϞϦʔɾϑοτϓϦϯ τ͕ఆৗύϑΥʔϚϯεΑΓॏཁͰ͢ɻ ͜ͷίϯύΠϥɺಉ͡ϝιουͷίϯύΠϧʹΑΓଟ͘ͷ ͕͔͔࣌ؒΓ·͢ ͓ΑͼΑΓଟ͘ͷϝϞϦʔΛফඅ͠·͢ ɻ ͨͩ͠ɺΫϥΠΞϯτɾίϯύΠϥͰੜͨ͠ίʔυΑΓ࠷ దԽ͞ΕͨϚγϯɾίʔυΛੜ͠·͢ɻ ΞϓϦέʔγϣϯ͕ఆৗʹୡͨ͠ޙɺ࣮ߦ࣌ύϑΥʔϚϯ ε্͕͠·͢ɻ ίϯύΠϧ࠷దԽ0SBDMF w ίϯύΠϧ͕ૣ͍ɺ͍ܰʢ$16.&.ʣ w ੑೳͦͦ͜͜ w ͍ॴ w ϥΠϑλΠϜ͕͍ʢ$MJFOU"QQMJDBUJPOʣ w "QQMJDBUJPO#PPUTUSBQ w ίϯύΠϧ͕͍ɺॏ͍ w ੑೳόϦόϦ w ͍ॴ w ϥΠϑλΠϜ͕͍ʢ4FSWFS"QQMJDBUJPOʣ w "GUFS#PPUTUSBQ
void deposit();} public static int moneyBox = 0; public class Nickel implements Coin { public void deposit() { moneyBox += 5; }} public class Dime implements Coin { public void deposit() { moneyBox += 10; }} public class Quarter implements Coin { public void deposit() { moneyBox += 25; }} public PolymorphismTest() { Coin nickel = new Nickel(); Coin dime = new Dime(); Coin quarter = new Quarter(); Coin coin = null; // change the variable maxImplementations to control the inlining behaviour // 2 = bimorphic dispatch - the method call will be inlined // 3 = megamorphic dispatch - the method call will not be inlined final int maxImplementations = 2; for (int i = 0; i < 1_000_000; i++) { switch (i % maxImplementations) { case 0: coin = nickel; break; case 1: coin = dime; break; case 2: coin = quarter; break; } coin.deposit(); } System.out.println("moneyBox:" + moneyBox); } public static void main(String[] args) { new PolymorphismTest(); } } 1PMZNPSQIJTN5FTUKBWB $PJO*OUFSGBDFʹͭͷ࣮Λ ͭ؆қͳςετΫϥε NBY*NQMFNFOUBUJPOTͰར༻ ͢Δ࣮ΫϥεΛ੍ޚ͍ͯ͠Δ
%JWFJOUP+7.+*5$PNQJMFS w $MJFOU4FSWFS$PNQJMFS w 5JFSFE$PNQJMBUJPO w +*58BUDIUPEFFQEJWF 1FSGPSNBODF5JQT w %FFQQJOHXBSNVQ w 5BLF$BSFPG#JOBSZ4J[F w 5BLF$BSFPG1PMZNPSQIJTN
w +7.+*5DPNQJMFSPWFSWJFX w 0QFO+%,1SJOU"TTFNCMZ w +*58BUDI w )PU4QPUQSP fi MJOHXJUI+*58BUDI w +BWB)PU4QPU&RVJWBMFOUTPG&YBDU7.'MBHT w 3FBEJOHBTTFNCMZGSPNUIF+7. w 1SJOU"TTFNCMZPVUQVUFYQMBJOFE