关于java中的this关键字 翻译为这个
this是一个引用,是一个变量,它保存了内存地址指向了自身,存储在堆内存的java对象内部
每创建一个对象就会有一个this保存在该创建的对象中
this在大多数情况下是可以省略不写的
this不可以在带有static的方法中使用
没有static关键字的变量被称为实例变量
没有static关键字的方法被称为实例方法 访问的时候 通过 引用. 来访问
this可以使用在什么位置:
1.可以使用在实例方法中,代表当前对象 【语法: this.】
2.可以使用在构造方法中,通过当前的构造方法调用其他的构造方法【语法: this(实参);】
注意:this()这种语法只能出现在构造函数的第一行,也就是只能出现一句
package com.bjpowernode.jave.Test01;
public class UserTest {
public static void main(String[] args) {
User u1 = new User();
u1.print();
User u2 = new User("lele", 2000, 6, 7);
u2.print();
}
}
class User{
String name ;
int year;
int mouth;
int day;
//有参数构造函数
public User(String name, int year, int mouth, int day) {
this.name = name;
this.year = year;
this.mouth = mouth;
this.day = day;
}
//无参数构造函数
//这里我们希望在调用无参数构造的时候可以输出默认值 默认用户 1970 1 1
//我们可以通过this来实现这一个功能
public User() {
this("默认用户",1970,1,1);
}
//打印输出函数
public void print() {
System.out.println(this.name+"的生日是"+this.year+"年"+this.mouth+"月"+this.day+"日");
}
}
package com.bjpowernode.jave.Test02;
public class Test {
public static void method1() {
doSome();//省略的方式调用doSome
Test.doSome(); //完整的方式调用doSome
Test t = new Test();
t.doOther(); //调用doOther
System.out.println(t.i);
}
public void method2() {
doSome();//省略的方式调用doSome
Test.doSome(); //完整的方式调用doSome
doOther();//省略的方式调用doOther
this.doOther(); //调用doOther
System.out.println(i); //省略的方法调用i
System.out.println(this.i); //完整的方法调用i
}
public static void main(String[] args) {
method1(); //省略调用method1
Test.method1(); //完整调用method1
Test t2 = new Test();
t2.method2(); //调用method2
}
int i= 10;
public static void doSome() {
System.out.println("doSome");
}
public void doOther() {
System.out.println("doOther");
}
}