博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java基础-this关键字
阅读量:7163 次
发布时间:2019-06-29

本文共 944 字,大约阅读时间需要 3 分钟。

示例代码

package com.runoob.test;class Cat{    String name;    int age;    String color;    public void set(String name,int age,String color){        this.name=name;//这里相当于把set方法形参name 赋值给这个类的属性(成员变量)name        this.age=age;        this.color=color;    }    public String toString(){        return"姓名:"+name+"\t年龄:"+age+"\t颜色"+color;    }    public Cat abc(){        return this;    }}public class A6_11 {    public static void main(String[] args){        Cat one = new Cat();        Cat two = new Cat();        one.set("第一只猫", 5, "黑色");//调用这个方法时,this就相当于one 可以这么理解 ==>one.name=第一只猫        two.set("第二只猫", 6, "紫色");        Cat three=new Cat();        three=two.abc();//这里就相当于three=two,因为two.abc()这个方法执行会return this也就是返回当前调用该方法的对象,也就是返回two        System.out.println(one);        System.out.println(two);        System.out.println(three);    }}

 

姓名:第一只猫 年龄:5 颜色黑色

姓名:第二只猫 年龄:6 颜色紫色
姓名:第二只猫 年龄:6 颜色紫色

转载于:https://www.cnblogs.com/youning/p/6702030.html

你可能感兴趣的文章