Java this指针的使用

Java中关键字this指针只能用于方法内,当一个对象被创建后,JVM就会给这个对象分配一个引用自身的指针,这个指针就是this。this只能在类中的非静态方法中使用,静态方法和静态代码块中不能出现this。this只和特定对象关联,不个类关联,所以同一个类的不同对象有不同的this。
使用范围:

  • 在方法内使用成员变量的时
  • 将当前对象传递给其他方法时
  • 在构造器中调用构造器时

示例

  1. 在方法中使用成员变量
public class person{
    private String name;
    private int age;
    private String email;

    person(String name,int age,String email){
        setName(name);
        setAge(age);
        setEmail(email);
        printInfo();
    }
    public void setName(String name){
        this.name=name;
    }
    public void setAge(int age){
        this.age=age;
    }
    public void setEmail(String email){
        this.email=email;
    }   
    public void printInfo(){
        System.out.println("name:"+name+",age:"+age+",email:"+email);
    }

    public static void main(String [] args){
        person p=new person("xiaoming",12,"xiaoming@email.com");
    }
}

运行结果:name:xiaoming,age:12,email:xiaoming@email.com

  1. 将当前对象传递给其他方法
class Person{
    public void eat(Apple apple){
        Apple peeled =apple.getPeeled();
        System.out.println("Yummy");
    }
}
class Peeler{
    static Apple peel(Apple apple){
        // ...remove peel
        return apple;//peeled
    }
}
class Apple{
    Apple getPeeled(){
        return Peeler.peel(this);
    }
}
public class PassingThis{
    public static void main(String [] args){
        new Person().eat(new Apple());
    }
}

运行结果:Yummy

  1. 在构造器中调用构造器
public class  Flower{
    int petalCount=0;
    String s ="initial value";
    Flower(int petals){
        petalCount=petals;
        System.out.println("Constructor w/int arg only,petalCount ="+petalCount);
    }
    Flower(String ss){
        System.out.println("Constructor w/ String arg only,s ="+ss);
        s=ss;
    }
    Flower(String s,int petals){
        this(petals);//可以用this调用一个构造器,但却不能调用两个,必须将构造器调用置于最起始处,否则会编译出错。
        //!can't call two
        this.s=s;//Another use of this
        petalCount=petals;
        System.out.println("Strng & int args");
    }
    Flower(){
        this("hi",47);
        System.out.println("default constructor (no args)");
    }
    void printPetalCount(){
        //!this (11),//not inside non-constructor 
        System.out.println("petalCount ="+petalCount+ "s="+s);
    }
    public static void main(String [] args){
        Flower x=new Flower();
        x.printPetalCount();
    }
}

运行结果:

Constructor w/ String arg only,s =47
Strng & int args
default constructor (no args)
petalCount =47s=hi

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值