/*看一下下面的程序,看是否你的答案和運行的答案是否一致! */ 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思想差不多,就是在多態的情況下有一些不同,c++基類中的方法如果沒有有virtual修飾,那么派生類的重寫該方法時就不是覆蓋,不會具有包含多態(c++多態的種類:強制多態、重載多態、類型參數化多態、包含多態(就是通過用virtual))!然而在java中,如果子類中重寫了父類的方法,那么就是覆蓋,就會產生像c++使用virtual的多態!c++樣例請點擊這里:here! 輸出結果: /* 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 */
?