当前位置:   article > 正文

JAVA this关键字

JAVA this关键字

this是JAVA的一个关键字,表示某个对象。this可以出现在实例方法和构造方法中,但不可以出现在类方法中。

1、在构造方法中使用this:

this关键字出现在类的构造方法中时,代表使用该构造方法创建的对象。举例:

package this关键字;

public class People {
    int leg,hand;
    String name;
    People(String s){
    	name=s;
    	this.init();//可以省略this,即将“this,init()”;写成“init()”
    }
    void init() {
    	leg=2;
    	hand=2;
    	System.out.println(name+"有"+hand+"只手"+leg+"条腿");
    }
	public static void main(String[] args) {
		People hsy=new People("后绍园");//创建hsy时,构造方法中的this就是对象hsy
	}

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

在这里插入图片描述

2、在实例方法中使用this:

实例方法只能通过对象来调用,不能用类名来调用。当this关键字出现在实例方法中时,this就代表正在调用该方法的当前对象。
注意:this不能出现在类方法中,这是因为类方法可以通过类名直接调用,这时,可能还没有任何对象诞生。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/563248
推荐阅读
相关标签
  

闽ICP备14008679号