zoukankan      html  css  js  c++  java
  • java基础-this关键字

    示例代码

    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+"	年龄:"+age+"	颜色"+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 颜色紫色

  • 相关阅读:
    bzoj 4361: isn
    bzoj 2560: 串珠子
    bzoj 3622: 已经没有什么好害怕的了
    UOJ #30. 【CF Round #278】Tourists
    Codeforces Round #452 E. New Year and Old Subsequence
    bzoj 2653: middle
    codeforces701C
    codeforces437C
    codeforces518B
    codeforces706C
  • 原文地址:https://www.cnblogs.com/youning/p/6702030.html
Copyright © 2011-2022 走看看