Java继承

Java继承

 1 public class Base{
 2     private String baseName = "base";
 3     
 4     public Base()
 5     {
 6         callName();
 7     }
 8  
 9     public void callName(){
10         System. out. println(baseName);
11     }
12  
13     static class Sub extends Base{
14         private String baseName = "sub";
15         public void callName()
16         {
17             System. out. println (baseName) ;
18         }
19     }
20     
21     public static void main(String[] args){
22         Base b = new Sub();
23     }
24 }
25 //输出为Null.子类实例化后,先执行父类中的方法,callName()调用了baseName,然而此时子类中的baseName还未赋值,输出为Null.
26 
27 
28 
29 public class C {
30      private String b = "c1";
31 
32      public C(){
33           System.out.println("c");
34           call();
35      }
36 
37      void call(){
38           System.out.println(b);
39      }
40 
41      static class D extends C{
42           private String b = "d1";
43 
44           public D(){
45                System.out.println("d");
46                call();
47           }
48 
49           void call(){
50                System.out.println(b);
51           }
52      }
53 
54      public static void main(String[] args){
55           C c = new D();
56      } 
57 }

 

print:

c

null

d

d1

 

子类不会继承父类的private属性和方法。

 

posted @ 2016-09-16 14:50  KIKI_FAN  阅读(138)  评论(0编辑  收藏  举报