java的继承与上溯


Java代码 

Java代码   收藏代码
  1. class Parent {  
  2. int i = 1;  
  3. String j = "Parent J";  
  4. StringBuffer k = new StringBuffer("Parent:");  
  5.   
  6. public String getJ() {  
  7. return j;  
  8. }  
  9.   
  10. public int getI() {  
  11. return i;  
  12. }  
  13.   
  14. public void printBuffer() {  
  15. k.append("Parent Buffer;");  
  16. System.out.println(k);  
  17. }  
  18.   
  19. static String getClassName() {  
  20. return "Parent";  
  21. }  
  22. }  
  23.   
  24. class Child extends Parent {  
  25. int i = 2;  
  26. String j = "Child J";  
  27. StringBuffer k = new StringBuffer("Child:");  
  28.   
  29. public String getJ() {  
  30. return j;  
  31. }  
  32.   
  33. public int getI() {  
  34. return -i;  
  35. }  
  36.   
  37. public void printBuffer() {  
  38. k.append("Child Buffer;");  
  39. System.out.println(k);  
  40. }  
  41.   
  42. static String getClassName() {  
  43. return "Child";  
  44. }  
  45. } </span>  

 




Java代码   收藏代码
  1. <span style="font-size: small;">public class ExtendDemo {  
  2.   
  3. public static void main(String[] args) {  
  4. Child child = new Child();  
  5. System.out.println("Child type test:");  
  6. System.out.println("child.i:" + child.i);  
  7. System.out.println("child.getI():" + child.getI());  
  8. System.out.println("child.j:" + child.j);  
  9. System.out.println("child.getJ():" + child.getJ());  
  10. child.printBuffer();  
  11. System.out.println("child.getClassName():" + child.getClassName());  
  12. System.out.println();  
  13.   
  14. Parent parent = child;  
  15. System.out.println("Parent type test:");  
  16. System.out.println("parent.i:" + parent.i);  
  17. System.out.println("parent.getI():" + parent.getI());  
  18. System.out.println("parent.j:" + parent.j);  
  19. System.out.println("parent.getJ():" + parent.getJ());  
  20. parent.printBuffer();  
  21. System.out.println("parent.getClassName():" + parent.getClassName());  
  22. }  
  23.   
  24. } </span>  

 

运行结果如下: 
Child type test: 
child.i:2 
child.getI():-2 
child.j:Child J 
child.getJ():Child J 
Child:Child Buffer; 
child.getClassName():Child 

Parent type test: 
parent.i:1 
parent.getI():-2 
parent.j:Parent J 
parent.getJ():Child J 
Child:Child Buffer;Child Buffer; 
parent.getClassName():Parent 

Child继承Parent,子类的变量和静态方法分别隐藏父类的变量和静态方法,子类的实例方法覆盖父类的实例方法。隐藏只是把父类的东东藏起来,但是其还是实质存在的;而覆盖就是把父类的东东完全抹掉以替换成子类的,是不可恢复的。在child被强制转换成Parent类型后,被隐藏的东西又被恢复了,而被覆盖的方法却是一去不复返了(子类的方法在这个实例里面永久替代了原先父类的方法)。这就是区别,也是这个题的考点所在了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值