this
什么是this?
this是Java中的关键字,当前对象的引用。
this如何使用?
- 在实例方法中使用
public class ThisTest {
int temp = 10;//成员变量
public void a(){
int temp = 20;//局部变量
System.out.println(this.temp);//本类中的成员变量 输出10
System.out.println("----------------------");
System.out.println(temp);//输出20
}
}
class Test{
public static void main(String[] args) {
ThisTest tt = new ThisTest();//创建对象
tt.a();
}
}
运行结果:
2. 在构造方法中使用
public class ThisTest {
int temp = 10;//成员变量
public ThisTest(int temp){
this.temp = temp;//将传进来的值赋值给本类中的成员变量
}
}
class Test{
public static void main(String[] args) {
//创建对象并调用该对象中需要传入一个int类型的值的构造方法
ThisTest tt = new ThisTest(30);
System.out.println(tt.temp);//输出30
//这里的结果为啥是30呢,我上面明明定义的是10
//因为在构造方法中使用了this.temp = temp; 将我们传入的30覆盖了原有的值了
}
}
运行结果:
static
什么是static?
static也是Java中的一个关键字,表示静态的,它可以用来修饰变量、方法、等,修饰变量时叫静态变量,修饰方法时叫静态方法。
静态变量
public class Test {
int a = 5;//(成员变量)全局变量
static int b = 10;//静态变量
//static的作用是共享给所有对象使用
//静态变量一般很少用,一般和final一起使用用来声明常量
final static int c = 20;
public static void main(String[] args) {
Test t = new Test();//创建对象
//要输出未加static的变量需要创建对象,使用对象名.变量名
System.out.println(t.a);//输出5
System.out.println(b);//输出10
System.out.println(c);//输出20
}
}
运行结果:
注意
静态方法
public class Test {
//非静态方法
public void method1(){
System.out.println("非静态方法");
}
//静态方法
public static void method2(){
System.out.println("静态方法");
}
public static void main(String[] args) {
Test t = new Test();//创建对象
t.method1();//未加static的方法就算是在同一个类中,需要调用时也是要创建对象的
method2();//加了static的方法可以直接使用方法名调用
//Test.method2();//有两种写法 类名.方法名
}
}
运行结果:
注意:
总结: 静态只能调用静态,非静态不仅可以调用非静态还可以调用静态,需要调用非静态的变量或方法需要创建对象,使用对象名.变量名或方法名。