java14天

来源:互联网 发布:筑家易网络办公 编辑:程序博客网 时间:2024/05/16 23:36

this关键字

  • 用于区分局部变量和成员同名的情况
  • 代表本类对象,即谁调用它,它代表引用它的对象
class  Persons//当new名与类名不一致时,java中方法声明无效,需要返回类型{    private String name;    Person(String name)    {        this.name=name;/*如p调用了persons这个类,并同时向person输入了"zeng"        此时的this.name=p.name*/    }    public void speak()    {        System.out.println("name="+name);    }}class action{    public static void main(String[] args)     {        Person p=new Person("zeng");        Person p1=new Person("jian");        p.speak();        p1.speak();    }}自我感觉的话,我觉得这个this十分的好用,无需写一些繁琐的代码,谁调用它,它就是谁.class compare1{    private int age;//定义了一个私有变量age    public boolean compare1(compare1 p)//定义了比较函数,返回布尔类型    {        return this.age==p.age;//将调用函数与传入数据的age进行比较    }}class demo1{    public static void main(String[] args)     {        compare1 p = new compare1(30);//new了一个对象p        compare1 p2 = new compare1(20);//new了一个对象p2        boolean b=p.compare1(p2);//将p与p2的age比较并最终赋给b        System.out.println(b);//打印b    }}

这里写图片描述

修改后

class compare1{    private int age;//定义了一个私有变量age    compare1(int age)//这里新增加了一个赋值,将传入的p.age,p1.age传入到age中    {        this.age=age;    }    public boolean compare1(compare1 p)//定义了比较函数,返回布尔类型    {        return this.age==p.age;//将调用函数与传入数据的age进行比较    }}class demo1{    public static void main(String[] args)     {        compare1 p = new compare1(30);//new了一个对象p        compare1 p2 = new compare1(30);//new了一个对象p2        boolean b=p.compare1(p2);//将p与p2的age比较并最终赋给b        System.out.println(b);//打印b    }}
0 0
原创粉丝点击