码迷,mamicode.com
首页 > 编程语言 > 详细

java中子类与父类中隐含的this引用的分析

时间:2014-09-09 22:57:49      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   java   ar   div   sp   

/*
    看一下下面的程序,看是否你的答案和运行的答案是否一致!
*/
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: 0

Parent::h()
Child f()
Child g()
Parent::y()
LOOK HERE: 10//输出的是父类中的x

Parent::h()
Child f()
Child g()
Parent::y()
LOOK HERE: 10//输出的是父类中的x
*/
 

 

java中子类与父类中隐含的this引用的分析

标签:style   blog   http   color   使用   java   ar   div   sp   

原文地址:http://www.cnblogs.com/hujunzheng/p/3963487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!