java this指针的作用

转载自:Java this指针的使用_胜利Fred的博客-CSDN博客
 

 定义
    指当前正在访问的这段代码的对象。this只能在类中的非静态方法中使用,静态方法和静态代码块中不能出现this。


作用
    当我们在一个类中写一个方法时,当传入的参数的参数名与该类的成员变量名相同,并且把参数赋值给与之同名的成员变量时,此时编译器并不知道到底是参数赋值给成员变量,还是成员变量赋值给参数;所以就有了this指针的诞生。当我们把this指针加上后,就是把传进来的参数赋值给变量。


 实例

    在方法中调用成员变量


public class StringBuffer_1 {
    private String name;
    private int age;
    private String sex;

    StringBuffer_1(String name, int age, String sex) {
        setName(name);
        setAge(age);
        setSex(sex);
        printinfo();
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void printinfo() {
        System.out.println("name:" + name + "\n" + "age:" + age + "\n" + "sex:" + sex);
    }

    public static void main(String[] args) {
        StringBuffer_1 stringBuffer_1 = new StringBuffer_1("kwy", 21, "女");
    }
}

    将当前对象传递给其他方法

 class Person{
    public void eat(Apple apple){
        Apple peeled=apple.getPeeled();
        System.out.println("nihao");
    }
}
class Peeled{
    static Apple peel(Apple apple){
        return apple;
    }
}
class Apple{
    Apple getPeeled(){
        return Peeled.peel(this);
    }
}
public class StringBuffer_1 {
    public static void main(String[] args) {
        new Person().eat(new Apple());
    }
}

 在构造器中调用构造器

 public class StringBuffer_1 {
    int petalCount=0;
    String s ="initial value";
    StringBuffer_1(int petals){
        petalCount=petals;
        System.out.println("Constructor w/int arg only,petalCount ="+petalCount);
    }
    StringBuffer_1(String ss){
        System.out.println("Constructor w/ String arg only,s ="+ss);
        s=ss;
    }
    StringBuffer_1(String s,int petals){
        this(petals);//可以用this调用一个构造器,但却不能调用两个,必须将构造器调用置于最起始处,否则会编译出错。
        this.s=s;
        petalCount=petals;
        System.out.println("Strng & int args");
    }

    StringBuffer_1(){
        this("hi",34);
        System.out.println("default constructor (no args)");
    }
    void printPetalCount(){
        System.out.println("petalcount="+petalCount+"s="+s);
    }


    public static void main(String[] args) {
        StringBuffer_1 si=new StringBuffer_1();
        si.printPetalCount();
    }
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值