关于子类继承父类后调用方法的问题

来源:互联网 发布:xp系统网络连接受限制 编辑:程序博客网 时间:2024/05/15 04:17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class ParentClass {
   public String msg = "I am a attribute in ParentClass.";
 
    public String getMsg() {
        return msg;
    }
}
 
 
class ChildrenClass extends ParentClass {
    public String msg = "I am a attribute in ChildrenClass.";
}
 
 
public class TestClass {
    public static void main(String[] args) {
         
        ParentClass p = new ParentClass();
        ChildrenClass c = new ChildrenClass();
 
        System.out.println(p.getMsg());
        System.out.println("");
        System.out.println(c.getMsg());//没有重写,还是调用父类中的方法。
    }
}

输出结果是:

I am a attribute in ParentClass.

I am a attribute in ParentClass.


在子类没有重写父类中的方法时,调用的是父类中的方法,在调用方法时,总是先去找有没有子类扩展的方法,如果没有就去父类中找,这里子类并没有扩展父类的方法。

自己重写了就调用自己的,自己没重写就调用父类的。

2,动态绑定

当创建子类的对象的时候(new 子类())  在左边给的是父类的引用,即 父类  引用名 = new 子类()

系统动态绑定了引用的实际类型。

0 0
原创粉丝点击