|
|
|
Every class in Java inherits a method called
toString()
from the root class
Object
that, if overridden, allows a print method such as
System.out.print
to directly print out an object of that class. In the following example, instead of
//PrintObj.java class User { private String name; private int age; public User( String str, int yy ) { name = str; age = yy; } public String toString() { //(A) return "Name: " + name + " Age: " + age; } } class Test { public static void main( String[] args ) { User us = new User( "Zaphod", 119 ); System.out.printin( us ); //
Name
: Zaphod Age: 119 //(B) } }
As a result, we can now directly supply a User argument to the System.out.println method in class Test, as we show in line (B).
We could use the same strategy in a C++ program; that is, equip a class with a
toString()
-like function that creates a string representation from the values of the data
//PrintObj.cc #include <iostream > #include <string> using namespace std; class User { string name; int age; public: User( string str, int yy ) { name = str; age = yy; } friend ostream& operator<<(ostream & os, const User& user) { //(C) os << "Name: " << user.name << " Age: " << user.age << endl; } }; int main() { User us( "Zaphod", 119 ); cout << us << endl; // Name: Zaphod Age: 119 //(D) return 0; }
|
|
|
|
|
|
When objects go out of scope
[7]
in
C++, they are automatically
//Dest.cc #include <iostream > using namespace std; class X {}; class Y { X* p; //(A) public: Y( X* q ) : p( new X(*q) ){} //(B) ~Y(){ delete p; } //(C) }; int main() { X* px = new X(); //(D) Y y( px ); //(E) delete px; //(F) return 0; }
As the variable
y
in line (D) goes out of
scope when the flow of execution hits the right
As will be explained in greater detail in Chapter
11, programmer-supplied destructors are needed particularly when an
object appropriates system resources that need to be freed up
before the object is destroyed. In our example here, construction
of an object of type
Y
in line (B) entails allocating
memory for an object of type
X
to which the data member
p
points. The system
Java's object destruction works very differently
from C++. If no
System.gc();
Before actually destroying an object, the
garbage collector executes the code in the
finalize()
method of the object
[7] See Section 7.7 of Chapter 7 for a discussion on the scope of an identifier in C++. As mentioned there, the scope of an identifier is that part of a program in which an identifier is recognized as declared.
[8]
The invocation
X
(*q)
in line
(B) is actually a call to the
copy
constructor
of class
X
for constructing a new object
of type
X
as a copy of a previously
|
|
|

Database Management Systems

Computer Organization and Design, Fourth Edition: The Hardware/Software Interface (The Morgan Kaufmann Series in Computer Architecture and Design)

Effective Java (2nd Edition)

Scripting with Objects: A Comparative Presentation of Object-Oriented Scripting with Perl and Python