直接打印类,调用的是继承的Object类的toString()方法,Object类的toString()方法是这样实现的:getClass().getName() + "@" + Integer.toHexString(hashCode())。也就是类名+@+类的hashcode值,所以要重写toString()方法才能打印自己想要的内容。

具体看如下代码:

 

public class TestToString { 
 private String a;
 
 
 public String getA() {
  return a;
 }
 public void setA(String a) {
  this.a = a;
 }
 

 public static void main(String[] args){
  TestToString t=new TestToString();
  t.setA("Bonnie");
  System.out.println(t);
 }
 
}

输出结果为:asi.TestToString@1175422

 

public class TestToString { 
 private String a;
 
 
 public String getA() {
  return a;
 }
 public void setA(String a) {
  this.a = a;
 }
 
 @Override
 public String toString(){
  return getA();
  
 }
 public static void main(String[] args){
  TestToString t=new TestToString();
  t.setA("Bonnie");
  System.out.println(t);
 }
 
}

输出结果为:Bonnie

相关文章:

  • 2022-03-10
  • 2021-06-14
  • 2021-05-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-07
  • 2022-12-23
猜你喜欢
  • 2021-09-10
  • 2022-12-23
  • 2021-12-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-23
相关资源
相似解决方案