java中子类与父类中隐含的this引用的分析
生活随笔
收集整理的這篇文章主要介紹了
java中子类与父类中隐含的this引用的分析
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
/*看一下下面的程序,看是否你的答案和運行的答案是否一致!
*/
class Parent{public int x;public Parent p;public Parent(){}public Parent(int x){this.x=x; p=this;}public void f(){System.out.println("Parent::f()"); }public void g(){System.out.println("Parent::g()");}public void h(){System.out.println("Parent::h()");f();g();y();System.out.println("LOOK HERE: " + x);}private void y(){System.out.println("Parent::y()");}
};class Child extends Parent{public int x;public Child(){}public Child(int x){ super(x+5);this.x=x;}public void f(){System.out.println("Child f()");}public void g(){System.out.println("Child g()"); }
};public class ThisDemo {public static void main(String[] args) {Child ch=new Child();ch.h();System.out.println();ch=new Child(5);ch.h();System.out.println();ch.p.h();}}其實c++this思想和java中的this思想差不多,就是在多態(tài)的情況下有一些不同,c++基類中的方法如果沒有有virtual修飾,那么派生類的重寫該方法時就不是覆蓋,不會具有包含多態(tài)(c++多態(tài)的種類:強制多態(tài)、重載多態(tài)、類型參數(shù)化多態(tài)、包含多態(tài)(就是通過用virtual))!然而在java中,如果子類中重寫了父類的方法,那么就是覆蓋,就會產(chǎn)生像c++使用virtual的多態(tài)!c++樣例請點擊這里:here!
輸出結(jié)果:
/*
Parent::h()
Child f()
Child g()
Parent::y()
LOOK HERE: 0Parent::h()
Child f()
Child g()
Parent::y()
LOOK HERE: 10//輸出的是父類中的xParent::h()
Child f()
Child g()
Parent::y()
LOOK HERE: 10//輸出的是父類中的x
*/
?
轉(zhuǎn)載于:https://www.cnblogs.com/hujunzheng/p/3963487.html
總結(jié)
以上是生活随笔為你收集整理的java中子类与父类中隐含的this引用的分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dc/ep是什么意思
- 下一篇: 中黄的师生比咋样啊?