Thinking in java 之:this关键字

来源:互联网 发布:教粤语的软件 编辑:程序博客网 时间:2024/05/21 19:28

this关键字:

this关键字只能在方法内部使用,指“调用方法的那个对象”的引用,this的用法和其他对象引用并无不同,但要注意,如果在方法内部调用同一个类的另一个方法,就不必使用this,直接调用即可。例如:

public class Dog {public void eat(){drink();}public void drink(){}}
在eat()内部,你可以写成this.drink();但无此必要,编译器会帮你自动添加。只有当需要明确指定对当前对象引用的时,才需要用到this关键字。

例如:在实体类中通过get,set方法的获取属性值的时候。

this关键字对于将当前对象传递给其他方法也很有用。例如:

class Person {public void eat(Apple apple){Apple peeledapple=apple.getPeeled();System.out.println("nice");}}class Peeler{//给苹果去皮static Apple getPeeled(Apple apple){return apple;}}class Apple{Apple getPeeled(){return Peeler.getPeeled(this);}}public class PassingThis{public static void main(String[] args) {new Person().eat(new Apple());}}
这里苹果将通过this关键字将自身传递给了外部方法。

通过this在构造器中调用构造器:

class Demo {public Demo() {}public Demo(String s) { System.out.println("ss");} public Demo(int i){ this(); System.out.println(1111); //构造器必须放在最前面,否则编译报错  this("ss");//编译报错,can't call two this();//编译报错,Constructor call must be the first statement in a constructor} void Ways(){ this("ss"); //编译报错,} public static void main(String[] args) {}}

上面的例子表明:

1.尽管可以用this调用一个构造器,但却不能在一个构造器中同时调用2个。

2.必须将构造器调用置于最起始处(也就是构造方法中的最前面),否则编译出错。

3.Ways()方法表明,除构造器之外,编译器禁止在其他任何方法中调用构造器。




0 0
原创粉丝点击