Wells Wells - 2 years ago 71
Java Question

Java beginner confused about usage of constructors

class Date {
private int year;
private String month;
private int day;

public Date() {
month = "January";
year = 1999;
day = 1;
} //End of Constructor 1

public Date(int year, String month, int day) {
setDate(year, month, day);
} //End of Constructor 2

public Date(int year) {
setDate(year, "January", 1);
} //End of Constructor 3

public void setDate(int year, String month, int day) {
this.year = year;
this.month = month;
this.day = day;
} //End of Constructor 4

public class Calendar {
public static void main(String[] args){
Date date1 = new Date(2009, "March", 3);
Date date2 = new Date(2010);
Date date3 = new Date();

In the code above, which constructors are called for date1, date2, and date3? How do you print the results of date1, date2, and date3 after the constructor has been called?

I tried System.out.println(date1) and so on but it gives me strange strings like [email protected]

I was expecting to see 2009 March 1 or something of that sort.

Answer Source

When you try to print object, its toString() method is called which is inherited by all java class from Object class (superclass of all java class by default). So you will have to override toString() method in your class if you need some specific contents of the object to be printed. By default, this method prints Class and its hash code. Since you have not overriden the toString(), the printed string contains object class and its hash code ( [email protected]). Your constructor calls are determined by the argument you pass to the constructor. Like in date1, you passed 3 parameter of type int,string and int in order. This matches your constructor 2 arguments which are of int, string and int. So in in your date1 object consturction, constructor 2 is called. similarly for date2, constructor 3 is called and for date3, default constructor i.e consturcot 1 is called.

The "constructor 4" you marked is not a constructor, it is simply a method. Constructor do not have return type.

Again , to print as you expected in your question, override toString() method in your class and format the result accordingly in that method to get expected result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download