Query:function of method toString()?

J

Jack Dowson

Hello Everyone:
I came across a demo yesterday,which use System.out.println(cla) to
print a sentence on screen.But "cla" here is a class name.There is only
one method in this class definede as:public String toString().
Here is my question:If a mehod like "public String to String()" defined
in a class,then the class name will represent a string in a String
context,right?

Any help will be greatly appreciated!
Dowson.
 
P

Patricia Shanahan

Jack said:
Hello Everyone:
I came across a demo yesterday,which use System.out.println(cla) to
print a sentence on screen.But "cla" here is a class name.There is only
one method in this class definede as:public String toString().
Here is my question:If a mehod like "public String to String()" defined
in a class,then the class name will represent a string in a String
context,right?

Any help will be greatly appreciated!
Dowson.

Java does not have a concept of "X context".

PrintStream has several println methods, including one that takes an
Object argument. If cla is a reference to some object,
System.out.println(cla) prints the result of that object's toString
method. That happens regardless of what other methods the class has.

EVERY object has a public String toString() method, either declared or
inherited, because Object declares public String toString().

However, I am not sure what you mean by '"cla" is a class name. The
following program, with a class name as println argument, does not
compile because of a syntax error:

public class MyClass {
public static void main(String[] args){
System.out.println(MyClass);
}
}

You can call println for the Class object associated with a class:

System.out.println(MyClass.class)

That prints the result of the toString method for the Class object for
MyClass, the word "class" followed by a space and the name of the class.

Note: Watch the capitalization. "class" means the general concept of a
class. "Class" means the class of the object the

Patricia
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,150
Latest member
MakersCBDReviews
Top