构造函数和对象未打印

时间:2016-11-24 03:21:24

标签: java object constructor

我正在尝试编写一个简单的程序,它接受一个构造函数,该构造函数具有与之关联的名字,姓氏和年龄,并在main方法中打印出来。没有错误,但是当我尝试打印构造函数时,它给了我这个...... Const @ 2a139a55

公共类Const {

private String firstName;
private String lastName;
private int age;
//MAIN METHOD
public static void main(String[] args)
{
    Const person = new Const("John" , "Smith", 45);
    System.out.println(person); 
}
//CONSTRUCTOR
public Const(String first, String last, int a)
{
    firstName = first;
    lastName = last;
    age = a;
}

/ ** 输出:Const @ 2a139a55 ** / }

2 个答案:

答案 0 :(得分:1)

在Const类

中添加toString()方法
search

答案 1 :(得分:0)

public static void main(String[] args)
{
 Const person = new Const("John" , "Smith", 45);
   person.show(person );
}

 public void show(Const const){
   System.out.println(person.FirstName +" "+person.lastName +" "person.age);
    }
   //CONSTRUCTOR
     public Const(String first, String last, int a)
    {
       firstName = first;
       lastName = last;
      age = a;
    }

当我理解这个问题时,你想要从参数化构造函数形成的对象中取出所有值。

因此,您可以打印对象数据成员的所有值。         的System.out.println(人) 将打印对象引用,如PersonQWW @ 12121。        的System.out.println(人) 如果更改toString()方法,将打印所有数据成员。

你能做的是:

      Class person {
     //main method
     //show method
     //constructor
     public String toString(){
          return firstName +" "+lastName +"   "+age;
      }
    }

现在

   System.out.println(person);

通过泄露所有数据成员来提供所需的输出。

相关问题