Olá pessoal esse é o meu primeiro post no fórum, já frequento o GUJ há algum tempo, porém nunca criei uma conta para interagir com a comunidade, os tópicos por si só já me auxiliavam nos meus problemas em relação ao Java, agora que eu iniciei um estudo intenso do Java, surgiu uma dúvida com um código em questão do livro Deitel, e se refere ao “this”, e eu nunca tinha visto esse tipo de referência antes e não consigo entender porque ele “acessa” um método especifico.
Segue o código:
Class Date
[code]public class Date
{
private int month; // 1-12
private int day; // 1-31 based on month
private int year; // any year
// constructor: call checkMonth to confirm proper value for month;
// call checkDay to confirm proper value for day
public Date( int theMonth, int theDay, int theYear )
{
month = checkMonth( theMonth ); // validate month
year = theYear; // could validate year
day = checkDay( theDay ); // validate day
System.out.printf(
"Date object constructor for date %s\n", this );
} // end Date constructor
// utility method to confirm proper month value
private int checkMonth( int testMonth )
{
if ( testMonth > 0 && testMonth <= 12 ) // validate month
return testMonth;
else // month is invalid
{
System.out.printf(
“Invalid month (%d) set to 1.”, testMonth );
return 1; // maintain object in consistent state
} // end else
} // end method checkMonth
// utility method to confirm proper day value based on month and year
private int checkDay( int testDay )
{
int[] daysPerMonth =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// check if day in range for month
if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
return testDay;
// check for leap year
if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
( year % 4 == 0 && year % 100 != 0 ) ) )
return testDay;
System.out.printf( "Invalid day (%d) set to 1.", testDay );
return 1; // maintain object in consistent state
} // end method checkDay
// return a String of the form month/day/year
public String toString()
{
return String.format( “%d/%d/%d”, month, day, year );
} // end method toString
}[/code]
Class Employee
public class Employee
{
private String firstName;
private String lastName;
private Date birthDate;
private Date hireDate;
// constructor to initialize name, birth date and hire date
public Employee( String first, String last, Date dateOfBirth,
Date dateOfHire )
{
firstName = first;
lastName = last;
birthDate = dateOfBirth;
hireDate = dateOfHire;
} // end Employee constructor
// convert Employee to String format
public String toString()
{
return String.format( "%s, %s Hired: %s Birthday: %s",
lastName, firstName, hireDate, birthDate );
} // end method toEmployeeString
} // end class Employee
Class test
[code]public class EmployeeTest
{
public static void main( String[] args )
{
Date birth = new Date( 7, 24, 1949 );
Date hire = new Date( 3, 12, 1988 );
Employee employee = new Employee( “Bob”, “Blue”, birth, hire );
System.out.println( employee );
} // end main
} // end class EmployeeTest
[/code]
Saída:
Date object constructor for date 7/24/1949
Date object constructor for date 3/12/1988
Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949
O que eu não entendo é porque, tanto a classe Employee como a classe Date, acessam o metódo toString(), no primeiro caso através do this (referenciado a propria classe, até ai ok).
Mas porque diabos entram no metódo toString() ? E EXCLUSIVAMENTE no metódo toString() ? Criei outro metódo String e eles não acessam ficam só mostrando numeros quando eu retiro os metódos de cada classe, o que é CONFUSO para mim, agradeceria muito se algum usuário mais experiente com a linguagem pudesse me esclarecer essas dúvida.
Obrigado pela atenção.

