Java Reference
In-Depth Information
local
String name
should be assigned the value it already has, and you have done nothing with the
instance variable name of the
Person
object. You must use the
this
keyword inside the constructor
to refer to the instance variable name. You are not required to use it in the
printName()
method,
but it is recommended to avoid ambiguity.
public class Person {
String name;
public Person(String name){
this.name = name;
}
public void printName(){
System.out.println(name);
}
}
Another case where you may need to use the
this
keyword is when you have overloaded the con-
structor method and want to explicitly call one constructor from within another constructor.
Imagine, for instance, that sometimes you need to construct a
Person
object but you do not know
their name. You could create another constructor with no parameters and use the
this
keyword to
call the one
String
parameter constructor with a default name.
public class Person {
String name;
public Person(){
this("Unknown");
}
public Person(String name){
this.name = name;
}
public void printName(){
System.out.println(name);
}
}
Again, you might think the
this
keyword is not necessary, as for this simple example, you could
make a no‐parameter constructor that assigns the name variable to
"Unknown"
itself, without using
the
this
keyword. However, when your constructor is more complex, with several statements and
perhaps some calculations, using the
this
keyword will limit redundancy, increase readability, and
prevent discrepancies between what different constructors accomplish. The next exercise allows you
to try method overloading using the
this
keyword.
Method Overloading
try it out
In this exercise, you expand the
Person
class from the examples to demonstrate the use of method over-
loading and the
this
keyword.
1.
If you do not already have a project in Eclipse for Chapter 7, create one now.
Search WWH ::
Custom Search