Java基础18-toString()方法、this关键字

1.toString()方法

  • 在java中,所有对象都有toString()这个方法
  • 创建类时没有定义toString方法输出对象时会输出哈希码值
  • 它通常只是为了方便输出,比System.out.println(xx),括号里面的"xx"如果不是String类型的话,就自动调用xx的toString()方法
  • 它只是sun公司开发java的时候为了方便所有类的字符串操作而特意加入的一个方法
 1 class Dog{
 2     String name;
 3     int age;
 4     //类里默认有toString方法,如果未定义输出哈希码值,也可以进行重写
 5     public String toString(){
 6         return "我的姓名:"+name+"我的年龄:"+age;
 7     }
 8 }
 9 public class Test1{
10     public static void main(String[] args){
11         String name=new String("小明");//String也是一个类
12         System.out.println(name);//对象也可以输出,是因为默认调用了toString(),name.toString()
13         Dog d=new Dog();
14         System.out.println(d);//所有对象都有toString方法,
15         
16     }
17 }

 2.this关键字

  • 在类的方法定义中使用this关键字代表使用该方法的对象的引用。
  • 有时使用this可以处理方法中成员变量和参数重名的问题
  • this可以看做一个变量,他的值是当前对象的引用
 1 class Dog{
 2     String name;//成员变量
 3     int age;
 4     String color;
 5     public void set(String name,int age,String color){
 6         this.name=name;//this.name,这个name为成员变量
 7         this.age=age;
 8         this.color=color;
 9     }
10     public String toString(){
11         return "我的姓名:"+this.name+"我的年龄:"+this.age+"我的颜色:"+this.color;
12     }
13     public Dog value(){
14         return this;//可以看做一个变量,他的值是当前对象的引用
15     }
16 }
17 public class Test1{
18     public static void main(String[] args){
19         Dog one=new Dog();
20         Dog two=new Dog();
21         Dog three=new Dog();
22         one.set("第一只狗",5,"黑色");
23         two.set("第二只狗",6,"白色");
24         System.out.println(one);
25         System.out.println(two);
26         three=two.value();
27         System.out.println(three);
28         
29     }
30 }

原文地址:https://www.cnblogs.com/shenhainixin/p/9981516.html