java面向对象(多态中成员的特点)
时间:2014-07-22 21:54 来源: 我爱IT技术网 作者:山风
java面向对象(多态中成员的特点)
2)非静态的成员函数
编译时,参阅变量所属的类,是否有要调用的方法?比如Fu类有method1、method2,那么编译通过;没有method3,编译失败。
运行时,参阅对象所属的类,是否有要调用的方法?比如Zi类有method1,那么运行自己的;没有就找父类,父类没有才报错。
小结:编译看左,运行看右。
- - - - - - - - - - - - - - - - - - - - - - - - - -
3)非静态的成员变量
参阅变量所属的类。看左
- - - - - - - - - - - - - - - - - - - - - - - - - -
4)静态的成员函数
同上。静态不需对象,已与所属类绑定。比如 Fu.method4()
- - - - - - - - - - - - - - - - - - - - - - - - - -
5)静态的成员变量
同上。
代码演示:
- class Fu
- {
- int num=5;
- static int numS=6;
- void method1()
- {
- System.out.println("f1");
- }
- void method2()
- {
- System.out.println("f2");
- }
- static void method4()
- {
- System.out.println("f4");
- }
- }
- class Zi extends Fu
- {
- int num=8;
- static int numS=9;
- void method1()
- {
- System.out.println("z1");
- }
- void method3()
- {
- System.out.println("z3");
- }
- static void method4()
- {
- System.out.println("z4");
- }
- }
- class Test
- {
- public static void main(String[] args)
- {
- //- - - - - - - - - - - - - - - - -
- //例1:继承
- //Zi z=new Zi(); //本类引用指向本类对象
- //z.method1(); //Zi类复写method1,返回z1
- //z.method2(); //Zi类继承Fu类method2,返回f2
- //z.method3(); //Zi类特有method3,直接返回z3
- //- - - - - - - - - - - - - - - - -
- //例2:多态
- //Fu f=new Zi(); //父类引用指向子类对象
- //f.method1(); //Zi类复写method1,返回z1
- //f.method2(); //Zi类继承Fu类method2,返回f2
- //f.method3(); //Fu类没有method3,编译失败
- //- - - - - - - - - - - - - - - - -
- //例3,面试
- //Fu f=new Zi();
- //System.out.println(f.num); //先在Fu类找num属性,直接返回5
- //Zi z=new Zi();
- //System.out.println(z.num); //先在Zi类找num属性,直接返回8
- //- - - - - - - - - - - - - - - - -
- //例4,面试
- //Fu f=new Zi();
- //f.method4(); //先在Fu类找methdo4,返回f4
- //Zi z=new Zi();
- //z.method4(); //先在Zi类找methdo4,返回z4
- //- - - - - - - - - - - - - - - - -
- //例5,面试
- Fu f=new Zi();
- System.out.println(f.numS); //先在Fu类找numS,返回6
- Zi z=new Zi();
- System.out.println(z.numS); //先在Zi类找numS,返回9
- }
- }
本文来源 我爱IT技术网 http://www.52ij.com/jishu/5653.html 转载请保留链接。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
