this关键字的作用(调用方法的那个对象):
1)可在方法的内部获得对当前对象的引用。即它只能在方法内部使用,表示对“调用方法的那个对象”的引用。如果在方法内部调用同一个类的另一个方法,就直接调用即可而不必使用this。
public class Apricot {
void pick() { /* ... */ }
void pit() { pick(); /* ... */ }
}
----------
public class Test {
public void fn1(){
fn2();
this.fn2();
}
public void fn2(){
System.out.println("fn2 is called");
}
public static void main(String[] args) {
new Test().fn1();
}
}
输出结果:
fn2 is called
fn2 is called
2)只有当需要明确指出对当前对象的引用时,才需要使用this关键字。
public class Leaf {
int i = 0;
Leaf increment() {
i++;
return this;//返回对当前对象的引用
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
//由于increment()通过this关键字返回对当前对象的引用,所有很容易对同一个对象执行多次操作
x.increment().increment().increment().print();
}
}
/* Output:
i = 3
*/
public class Test {
private int a;
public Test(int a) {
this.a = a;
System.out.println(this.a);
}
public Test(int a,String s) {
this(a);//使用this在构造器中调用构造器
System.out.println(a + " " + s);
}
public static void main(String[] args) {
new Test(100,"abc");
}
}
程序输出结果:
100
100 abc
结果分析:创建两个重载构造器,可在一个构造器通过this调用另一个构造器,且必须将构造器调用至于最起始处,否则编译器会报错。
static关键字的含义:satatic方法就是没有this的方法,在static方法的内部不能调用非静态方法,反过来倒是可以的。两个都是静态方法或者两个都是非静态方法则相互调用。
public class Test {
public static void fn1(){
System.out.println("在非静态方法的内部能调用static方法");
}
public void fn2(){
fn1();
}
public static void main(String[] args) {
new Test().fn2();
}
}
输出结果:在非静态方法的内部能调用static方法
而且在没有创建任何对象的情况下,可通过类名调用static方法。
public class Test {
public static void fn(){
System.out.println("在没有创建类对象的前提下调用static方法");
}
public static void main(String[] args) {
Test.fn();
}
}