java this关键字介绍,面向对象编程_10_this的用法_this调用构造方法,java this关键字最常的用法,以及使用时的注意事项:
在一般的方法中,this关键字总是指向调用该方法的对象。
在java构造方法中,this总是指向正要初始化的对象。
java this关键字最常的用法:
1. 让类中的一个方法,访问该类的另一个方法或属性。
2. 使用this关键字调用重载构造方法。避免相同的初始化代码,只能在构造方法中用,并且一定要位于构造方法的第一句。
this使用时的注意事项:
·this不能用于static方法!(this指向当前对象,static方法跟对象没有任何的的关系)
this代码实例
package cn.bjsxt.oop.testThis;
public class Student {
String name;
int id;
public Student(String name,int id){
this(name); //通过this调用其他构造方法,必须位于第一句! Constructor call must be the first statement in a constructor
this.name = name;
this.id = id;
}
public Student(String name){
this.name = name;
}
public Student(){
System.out.println(“构造一个对象”);
}
public void setName(String name){
this.name = name;
}
public void study(){
this.name= “张三”;
System.out.println(name+”在學習”);
}
public void sayHello(String sname){
System.out.println(name+”向”+sname+”說:你好!”);
}
}