this指的是当前对象,“this.方法 ”就是当前对象调用的方法,“this.变量" 指的是当前对象的变量。
练习代码如下:
package com.imooc;
public class Telephone {
private float screen;
private float cpu;
private float mem;
public void sendMessage() {
System.out.println("sendMessage");
}
public float getScreen() {
return screen;
}
public void setScreen(float screen) {
this.screen = screen;
this.sendMessage();
}
public float getCpu() {
return cpu;
}
public void setCpu(float cpu) {
this.cpu = cpu;
}
public float getMem() {
return mem;
}
public void setMem(float mem) {
this.mem = mem;
}
public Telephone() {
System.out.println("com.imooc.Telephone无参的构造方法执行了。");
}
public Telephone(float newScreen,float newCpu,float newMem) {
screen = newScreen;
cpu = newCpu;
mem = newMem;
System.out.println("有参的构造方法执行了!");
}
}
调用Telephone:
package com.imooc;
public class initialTelphone {
public static void main(String[] args) {
// TODO 自动生成的方法存根
//无参方法创建对象
Telephone phone = new Telephone();
//有参方法创建对象,并给对象中的实例变量赋初值
Telephone phone2 = new Telephone();
phone2.setScreen(8.0f);
System.out.println("screen:" + phone2.getScreen());
}
}
执行结果:
com.imooc.Telephone无参的构造方法执行了。
com.imooc.Telephone无参的构造方法执行了。
sendMessage
screen:8.0