·调用属性(代码示例):
public class thisDemo01 {
public static void main(String[] args) throws Exception {
BlueMoon bm=new BlueMoon("渣渣辉", 100);
System.out.println(bm.getInfo());
}
}
class BlueMoon {
private String name;
private int level;
public BlueMoon(String name, int level) {
this.name = name;
this.level = level;
}
public String getInfo() {
return "大家好!我是" + this.name + ",我是贪玩蓝月的战士,等级:" + this.level;
}
}
·调用方法(普通方法与构造方法)
|—调用普通方法:
public class thisDemo01 {
public static void main(String[] args) throws Exception {
BlueMoon bm = new BlueMoon("渣渣辉", 100);
System.out.println(bm.getInfo());
}
}
class BlueMoon {
private String name;
private int level;
public BlueMoon(String name, int level) {
this.name = name;
this.level = level;
}
public void print() {
System.out.println("************************");
}
public String getInfo() {
this.print();//调用普通方法
return "大家好!我是" + this.name + ",我是贪玩蓝月的战士,等级:" + this.level;
}
}
|—调用构造方法:
public class thisDemo01 {
public static void main(String[] args) throws Exception {
BlueMoon bm1 = new BlueMoon();
BlueMoon bm2 = new BlueMoon("古天乐");
BlueMoon bm3 = new BlueMoon("小志传奇", "陈赫", "法师");
System.out.println(bm1.getInfo());
System.out.println(bm2.getInfo());
System.out.println(bm3.getInfo());
}
}
class BlueMoon {
private String game;
private String name;
private String title;
private int level;
public BlueMoon() {
this("贪玩蓝月", "无名氏", "未定", 0);
}
public BlueMoon(String name) {
this("贪玩蓝月", name, "剑士", 90);
}
public BlueMoon(String game, String name) {
this(game, name, "战士", 100);
}
public BlueMoon(String game, String name, String title) {
this();
this.game = game;
this.name = name;
this.title = title;
}
public BlueMoon(String game, String name, String title, int level) {
this.game = game;
this.name = name;
this.title = title;
this.level = level;
}
public String getInfo() {
return "欢迎来到" + this.game + "!我是" + this.name + ",职业:" + this.title + ",等级:" + this.level + "级";
}
}
·当前对象调用:
class BlueMoon {
public void print() {
//哪个对象调用了print()方法,this就自动与此对象指向同一块内存地址
System.out.println("this=" + this);//this 就是当前调用对象
}
}
public class thisDemo02 {
public static void main(String[] args) throws Exception {
BlueMoon bm = new BlueMoon();
BlueMoon bm2 = new BlueMoon();
System.out.println("bm=" + bm);
bm.print();
System.out.println("---------------------");
System.out.println("bm2=" + bm2);
bm.print();
}
}