Picking up an OOP(1) -JAVA-Inheritance

来源:互联网 发布:php 自动化部署工具 编辑:程序博客网 时间:2024/06/05 06:42

一个不错的的栗子:

public class A {    public String show(D obj) {        return ("A and D");    }    public String show(A obj) {        return ("A and A");    } }public class B extends A{    public String show(B obj){        return ("B and B");    }    @override public String show(A obj){        return ("B and A");    } }public class C extends B{}public class D extends B{}public class Test {    public static void main(String[] args) {        A a1 = new A();        A a2 = new B();        B b = new B();        C c = new C();        D d = new D();        System.out.println("1--" + a1.show(b));        System.out.println("2--" + a1.show(c));        System.out.println("3--" + a1.show(d));        System.out.println("4--" + a2.show(b));        System.out.println("5--" + a2.show(c));        System.out.println("6--" + a2.show(d));        System.out.println("7--" + b.show(b));        System.out.println("8--" + b.show(c));        System.out.println("9--" + b.show(d));          }}// below is std out1--A and A2--A and A3--A and D4--B and A5--B and A6--A and D7--B and B8--B and B9--A and D

Found this example from someone’s blog, which perfectly shows some edge conditions needed to be cared about. I think what explained in that blog is not cristal clear and personally modified some. Here is mine version. Take a look at the 3rd, 4th, 5th and the last one.

        System.out.println("3--" + a1.show(d));        System.out.println("4--" + a2.show(b));        System.out.println("5--" + a2.show(c));        System.out.println("9--" + b.show(d));  

pirority: this.show(O)、super.show(O)、this.show((super)O) super.show((super)O)
which ‘show’ here just for representing some method.
Polymorphism in JAVA is simple needless of too many words. It pick up the most specific method. Take a look at the 4th one: a2 is a object of type A class and constructed as type B. (can I say that???????)

When call method with input type B, no method show find with input type B -> therefor follows the pirority ->this.show((super)) which invoke a2.show(A). However show(A) in A is overrided by B. And finally called show(A) method in B. -> which is exactly most specific method.

Notation

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

0 0
原创粉丝点击