Java中的继承简单说明 [英] Inheritance in Java simple clarification

查看:45
本文介绍了Java中的继承简单说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有这个:

public class A {

    public int a = 0;
    public void m(){
        System.out.println("A"+a);
    }
}

这:

public class B extends A {

    public int a = 5 ;
    public void m (){
        System.out.println("B"+a);
    }
    public static void main(String[] args) {
        A oa = new A();
        B ob = new B();
        A oab = ob;
        oa.m();
        ob.m();
        oab.m();

        System.out.println("AA"+oa.a);
        System.out.println("BB"+ob.a);
        System.out.println("AB"+oab.a);
    }
}

输出:

A0
B5
B5
AA0
BB5
AB0


我不明白为什么 oab.m(); 输出是 B5 而不是 A0 .谁可以给我解释一下这个?


I don't understand why oab.m(); output is B5 instead of A0. Can someone explain this to me?

推荐答案

这就是多态的全部要点. oab的具体类型为B(因为使用new B()创建了对象).因此调用了B.m()方法.

That's the whole point of polymorphism. The concrete type of oab is B (since the object was created with new B()). So the method B.m() is called.

http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29中查看动物示例了解其用途.如果您有一只动物,而这只动物是一只猫,您会期望它说喵!"当你说话时.

Look at the Animal example in http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29 to understand why it's useful. When you have an animal, and this animal is a Cat, you expect it to say "Meow!" when you make it talk.

这篇关于Java中的继承简单说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆