JAVA_Java中关于supper和this的理解

2015-04-04 Created By BaoXinjian

一、摘要


 

二、解析


 

 1 package cn.galc.test;
 2 
 3 /**
 4  * 父类
 5  * @author gacl
 6  *
 7  */
 8 class FatherClass {
 9     public int value;
10     public void f() {
11         value=100;
12         System.out.println("父类的value属性值="+value);
13     }
14 }
15 
16 /**
17  * 子类ChildClass从父类FatherClass继承
18  * @author gacl
19  *
20  */
21 class ChildClass extends FatherClass {
22     /**
23      * 子类除了继承父类所具有的valu属性外,自己又另外声明了一个value属性,
24      * 也就是说,此时的子类拥有两个value属性。
25      */
26     public int value;
27     /**
28      * 在子类ChildClass里面重写了从父类继承下来的f()方法里面的实现,即重写了f()方法的方法体。
29      */
30     public void f() {
31         super.f();//使用super作为父类对象的引用对象来调用父类对象里面的f()方法
32         value=200;//这个value是子类自己定义的那个valu,不是从父类继承下来的那个value
33         System.out.println("子类的value属性值="+value);
34         System.out.println(value);//打印出来的是子类自定义的那个value的值,这个值是200
35         /**
36          * 打印出来的是父类里面的value值,由于子类在重写从父类继承下来的f()方法时,
37          * 第一句话“super.f();”是让父类对象的引用对象调用父类对象的f()方法,
38          * 即相当于是这个父类对象自己调用f()方法去改变自己的value属性的值,由0变了100。
39          * 所以这里打印出来的value值是100。
40          */
41         System.out.println(super.value);
42     }
43 }
44 
45 /**
46  * 测试类
47  * @author gacl
48  *
49  */
50 public class TestInherit {
51     public static void main(String[] args) {
52         ChildClass cc = new ChildClass();
53         cc.f();
54     }
55 }

 

 

 

Thanks and Regards

posted on 2015-04-10 22:54  东方瀚海  阅读(634)  评论(0编辑  收藏  举报