Java Reference
In-Depth Information
Notice that a constructor is simply a function like any other function, and it can
also be called as a function without using the new keyword. The outcome may be very
different, depending on how the function is written. I will discuss such scenarios shortly.
The keyword this inside a constructor refers to the object being constructed when
the function is called with the new operator. In this case, this.fName inside the Person
function refers to the fName property of the new object being constructed. So are lName
and toString . The Person constructor simply adds three properties to the object being
created. The following snippet of code creates two objects using the Person constructor
and prints their string representations:
// Create few Person objects
var john = new Person("John", "Jacobs");
var ken = new Person("Ken", "McEwen");
// The print() function calls the toString() method when
// it needs to convertan object to a string
print(john);
print(ken);
John Jacobs
Ken McEwen
Let's try using Person simply as a function, not as a constructor:
// Print details
printf("fName = %s, lName = %s", this.fName, this.lName);
// Call the Person function
var john = Person("John", "Jacobs");
// Print details
printf("fName = %s, lName = %s, full name = %s", this.fName, this.lName,
this.fullName());
// Call the Person function
var ken = Person("Ken", "McEwen");
// The print two person references
print("john = " + john);
print("ken = " + ken);
printf("fName = %s, lName = %s, full name = %s", this.fName, this.lName,
this.fullName());
 
Search WWH ::




Custom Search