public class thisShiyong {
public void jump() {
System.out.println("jump方法");
}
public void run() {
System.out.println("run方法");
//this.jump();// thisShiyong a=new thisShiyong(); a.jump();
jump();
}
public static void main(String[] args) {
thisShiyong dog=new thisShiyong();
dog.run();
}
}
成员方法run()使用成员方法jump()方法时,必须用对象去调用。没有使用static修饰的成员变量和成员方法都必须用对象去调用。
在run()方法中调用jump()方法,可以使用this去调用,而不必要在run()方法中再新建一个对象去调用jump方法。
但是Java允许对象的一个成员去调用另一个成员,而省略this前缀。因此可以把this省略。直接使用jump();
其实省略this是一种假象,一般,如果调用static修饰的成员(包括方法、成员变量)省略了前面的主调,那么默认使用类作为主调;
因此static修饰的方法中,只能调用static 修饰的成员,不允许使用this调用普通成员(如在static main()函数中不能直接使用this调用普通方法)。
如果没有static修饰的成员(包括方法、成员变量)省略前面的主调,那么默认使用this作为主调。
Java中的this,this总是指向调用该方法的对象。根据this出现的位置不同,this作为对象的默认引用有两种情况:
1.构造器中引用该构造器正在初始化的对象
2.在方法中调用该方法的对象。
总而言之,this就是让类中的一个方法,访问该类里的另一个方法或实例变量。
public class thisShiyong {
public String name;
public String color;
public double weight;
public thisShiyong() {}
public thisShiyong(String name,String color) {
this.name=name;
this.color=color;
}
public thisShiyong(String name,String color,double weight) {
this(name,color);
this.weight=weight;
}
public static void main(String[] args) {
thisShiyong dog=new thisShiyong();
}
}
为了在构造器B中使用构造器A中的初始化代码,又不用重新创建Java对象,可以使用this关键字来调用相应的构造器。
上代码中第三个构造器中使用了第二个构造器,直接使用this(name,color)。
使用this调用另一个重载的构造器只能在构造器中使用,而且必须作为构造器执行的第一条语句。