首页 > 其他 > 详细

关于this

时间:2014-11-06 19:14:35      阅读:227      评论:0      收藏:0      [点我收藏+]

this是指当前类的实例对象

 

 1 public class A {
 2     public void init()
 3     {
 4         System.out.println("1、A init");
 5         this.dosomething();
 6     }
 7        
 8     public void dosomething()
 9     {
10         System.out.println("2、A dosomething");
11     }
12 }
 1 public class B  extends A{
 2     public void init()
 3     {
 4         System.out.println("3、B init");
 5         super.init();
 6     }
 7        
 8     public void dosomething()
 9     {
10         System.out.println("4、B dosomething");
11     }
12        
13     public static void main(String[] args) {
14         B b=new B();
15         b.init();    
16     }

bubuko.com,布布扣

为什么会是这个结果??

这是因为如果是无参函数,那么有一个默认的参数是this,也就是类的实例对象

    super.init(),实际是super.init(b)

那么

    在类A中this.dosomething,就是A.dosomething(),所以结果就是3 1 4

public String name="tom";
    public void init()
    {
        System.out.println(this.name);
    }
public String name="jack";
    public void init()
    {  
        super.init();
        System.out.println(this.name);
    }
 
    public static void main(String[] args) {
        B1 b=new B1();
        b.init();  
         
        System.out.println(b.name);
         
        A1 a=new B1();
        a.init();  
         
        System.out.println(a.name);
    }

bubuko.com,布布扣

这里的运行结果为什么又不符合上面说的默认参数是一个this的实例对象呢?

这是因为:

成员变量编译运行看左面

成员方法编译看左面,运行看右面

关于this

原文:http://www.cnblogs.com/liuwt365/p/4079447.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!