Reputation: 1
I am trying to write a simple program that takes a constructor that has a first name, last name, and age associated with it and print it out in the main method. There are no errors but when I try to print the constructor it gives me this... Const@2a139a55
public class 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;
}
/** Output: Const@2a139a55 **/ }
Upvotes: 0
Views: 36
Reputation: 144
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;
}
As I understood the question , you want to take out all the values from an object formed by paramertized constructor.
Thus you can print all the values of an object data memebers. System.out.println(person) will print object reference like PersonQWW@12121. System.out.println(person) will print all the data members if you change the toString() method.
What you can do is :
Class person {
//main method
//show method
//constructor
public String toString(){
return firstName +" "+lastName +" "+age;
}
}
Now
System.out.println(person);
Will give desired out put by spilling out all data members.
Upvotes: 0
Reputation: 614
Add toString() method within the Const class
@Override
public String toString(){
return this.firstName + " " + this.lastName + " " + this.age;
}
Upvotes: 1