所有static关键字修饰的都是与类相关的,都是采用“类名.”的方式进行访问。因此不需要new对象
static修饰的方法:静态方法
static修饰的变量:静态变量
变量的分类
变量根据声明时所处位置不同进行划分
当在 方法体 中声明的变量叫:局部变量
当在 方法体外 声明的变量叫:成员变量
this关键字
1. this的类型 : 哪个对象调用就是哪个对象的引用类型(除了基本变量类型(int,double等)之外的所有数据类型(通过class定义的类型))
this用法
1. this.data; //访问属性
2. this.func(); //访问方法
3. this(); // 调用本类中其他构造方法
例
1. this.data
这种是在成员变量方法中使用
package first;
class MyTime {
public int day;
public int hour;
public int second;
public void setTime(int day,int hour, int second) {
day=day; //没有加上this
hour=hour; //没有加上this
second=second; //没有加上this
}
public void getTime() {
System.out.println("这是第"+day+"天的"+hour+"时"+second+"秒");
}
}
public class Day01 {
public static void main(String[] args) {
MyTime i=new MyTime();
i.setTime(23,23,27);
i.getTime();
}
}
程序运行后输出
产生的问题
当加上this时
此时即实现赋值的功能
2. this.func()
这种指在普通成员变量方法中使用this调用另外一个成员方法
package first;
class MyTime {
public int day;
public int hour;
public int second;
public void setTime(int day,int hour, int second) {
this.day=day;
this.hour=hour;
this.second=second;
}
public void getTime() {
System.out.println("这是第"+day+"天的"+hour+"时"+second+"秒");
this.getTime1();
}
public void getTime1() {
System.out.println("明天是一个好天气!");
}
}
public class Day01 {
public static void main(String[] args) {
MyTime i=new MyTime();
i.setTime(23,23,27);
i.getTime();
}
}
输出结果
3. this()
这种指在构造方法中使用this调用本类中的其他构造方法
package first;
class MyTime {
public int day;
public int hour;
public int second;
public MyTime () {
this(23,23,37);//调用本类中带有三个参数的构造方法
System.out.println("这是不含参数");
}
public MyTime(int day,int hour, int second) {
this.day=day;
this.hour=hour;
this.second=second;
System.out.println("三个含参数的构造方法");
}
public void show() {
System.out.println("这是第"+day+"天的"+hour+"时"+second+"秒");
}
}
public class Day01 {
public static void main(String[] args) {
MyTime i=new MyTime();
i.show();
}
}
运行结果
注意
1. this只可以在构造方法中调用其他构造方法
2. this必须放在第一行
3. 一个构造方法中只能调用一个构造方法