看板 java 關於我們 聯絡資訊
※ 引述《broodstare (交給C4就對了)》之銘言: : ======================================================================== : class Base2{ : private void foo(){ : System.out.println("Base2"); : } : } : class Derived2 extends Base2{ : public void foo(){ : System.out.println("Derived2"); : } : } : public class Practice { : static void basefoo(Base2 b){ : b.foo();● : } : static void derivefoo(Derived2 d){ : d.foo(); : } : public static void main(String[] args) { : basefoo(new Derived2()); : derivefoo(new Derived2()); : } : } 剛試了一下印證我的想法.... 如果這個例子是在教你多型,誠懇建議你換教材學 Java, 這個例子根本連編譯都過不了,更別說執行。 編譯器會直接告訴你找不到 Base2 的 foo 方法, 這不令人意外因為 Base2 的 foo 本來就是 private 方法。 實驗過程中倒是意外發現有趣的事,以下這個相似的例子,結果卻能執行, 命令列會印出 private foo public foo 請問各位鄉民們會怎麼解釋這個結果? public class PolyTest { public static void runBase(Base base){ base.foo(); } public static void runDes(Descendent des){ des.foo(); } public static void main(String[] args){ PolyTest poly = new PolyTest(); runBase(poly.new Descendent()); runDes(poly.new Descendent()); } public class Base { private void foo(){ System.out.println("private foo"); } } public class Descendent extends Base{ public void foo(){ System.out.println("public foo"); } } }// polyTest end -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.167.102.112
lovdkkkk:與 inner class 的私有物可以互通 12/27 19:37
broodstare:謝謝大大!! 我也來想一下 12/27 23:27
LaPass:inner class基本上無視privite之類的描述,因為都是同個物 12/28 01:10
LaPass:件 12/28 01:11