JAVA基础(多态访问特点)


 

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,多态中的成员访问特点之成员变量

【1】成员变量

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

  • Father   a  =  new  son ();

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

Father   a  =  new  son ();

 

2,多态中的成员访问特点之成员方法

【1】成员方法

  • 也叫动态绑定。  编译的时候会看父类里面有没有print()方法。如果没有则报错

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

 

 

 

3,多态中的成员访问特点之静态成员方法

【1】静态方法

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

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

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

  • 静态也可以类名。方法名。调用。所以在多态中。Father  F  = new Son ()。   F。method 相当于 Father 。方法名直接调用。

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兴帅_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值