Java编程思想之this关键字和static关键字

this关键字的作用(调用方法的那个对象):
    1)可在方法的内部获得对当前对象的引用。即它只能在方法内部使用,表示对“调用方法的那个对象”的引用。如果在方法内部调用同一个类的另一个方法,就直接调用即可而不必使用thispublic 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();
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值