JAVA basis (multi-state access features)


 

class Demo2_Polymorphic {

    public static void main(String[] args) {

        /*Father f = new Son();                    //父类引用指向子类对象

        System.out.println(f.num);





        Son s = new Son();

        System.out.println(s.num);*/





        Father f = new Son();

        //f.print();

        f.method();                                //相当于是Father.method()

    }

}

/*

成员变量

编译看左边(父类),运行看左边(父类)

成员方法

编译看左边(父类),运行看右边(子类)。动态绑定

静态方法

编译看左边(父类),运行看左边(父类)。

(静态和类相关,算不上重写,所以,访问还是左边的)

只有非静态的成员方法,编译看左边,运行看右边

*/

class Father {

    int num = 10;

    public void print() {

        System.out.println("father");

    }





    public static void method() {

        System.out.println("father static method");

    }

}





class Son extends Father {

    int num = 20;





    public void print() {

        System.out.println("son");

    }





    public static void method() {

        System.out.println("son static method");

    }

}



 

1, the characteristics of the multi-state visit of members of the member variables

[1] member variables

  • Compile look to the left (parent), run to the left to see the (parent).

  • Father   a  =  new  son ();

Compile look to the left (parent), run to the left to see the (parent).

Father   a  =  new  son ();

 

2, the polymorphic characteristics of the member access member methods

[1] member method

  • Also known as dynamic binding. Compile time will see the parent class there are no print () method. If not then an error

  • Compile look to the left (parent), run to the right to see (subclass).

 

 

 

3, multi-state member access features of the static member methods

[1] static methods

  • Compile look to the left (parent), run to the left to see the (parent).

  • (Static and class-related, not really rewrite, so the visit is to the left of)

  • Only non-static member method, the compiler look left, look to the right to run

  • Static can also be the class name. Method name. transfer. Therefore, in the multi-states. Father F = new Son (). F. method equivalent to the Father. Method name called directly.

class Father {

    int num = 10;

    public void print() {

        System.out.println("father");

    }





    public static void method() {

        System.out.println("father static method");

    }

}





class Son extends Father {

    int num = 20;





    public void print() {

        System.out.println("son");

    }





    public static void method() {

        System.out.println("son static method");

    }

}

        

 

 

 

 

Guess you like

Origin blog.csdn.net/Cricket_7/article/details/92062058