Children.java: ---------------------------------------- public class Children { public void one() { System.out.println("Children one"); } public void two() { System.out.println("Children two"); } } ---------------------------------------- Boy.java: ---------------------------------------- public class Boy extends Children { public void one() { System.out.println("Boy one"); } public void two() { System.out.println("Boy two"); } public void three() { System.out.println("Boy three"); } } --------------------------------------- Test.java ---------------------------------------- public class Test { public static void main(String[] argv) { Children bb = new Boy(); bb.one(); bb.two(); // (Boy)bb.three(); } } ------------------------------------------ 这样的输出结果是 boy one boy two如果我把//去掉,就会提示我not a statement at line xxx我糊涂了:(
改成这样就可以了 --------------------------------------- Test.java ---------------------------------------- public class Test { public static void main(String[] argv) { Children bb = new Boy(); bb.one(); bb.two(); ((Boy)bb).three(); } }
(Boy)bb.Three();
而且其他两个方法直接用就行了
Children =汽车
Boy 当然是轿车当然也是汽车
隐藏实现
为什么要用(Boy)bb.Three()呢?难道bb还不是一个真正的Boy()对象?
而Children的对象又不应该具有three()方法。所以,我糊涂了:)
----------------------------------------
public class Children {
public void one() {
System.out.println("Children one");
}
public void two() {
System.out.println("Children two");
}
}
----------------------------------------
Boy.java:
----------------------------------------
public class Boy extends Children {
public void one() {
System.out.println("Boy one");
}
public void two() {
System.out.println("Boy two");
}
public void three() {
System.out.println("Boy three");
}
}
---------------------------------------
Test.java
----------------------------------------
public class Test {
public static void main(String[] argv) {
Children bb = new Boy();
bb.one();
bb.two();
// (Boy)bb.three();
}
}
------------------------------------------
这样的输出结果是
boy one
boy two如果我把//去掉,就会提示我not a statement at line xxx我糊涂了:(
---------------------------------------
Test.java
----------------------------------------
public class Test {
public static void main(String[] argv) {
Children bb = new Boy();
bb.one();
bb.two();
((Boy)bb).three();
}
}