问题
I have a have a class that has a method which takes a string. Then I have a method which returns the value of the above method. When ever I get the return value in my main class and print it the printed value is "ExamQuestion@143c8b3". How do I get it to print correctly?
Thanks
回答1:
Whenever you get the format "@" this is the default format of an object's toString() method.
Calling System.out.println(question);
calls ExamQuestion.toString()
. If the method isn't overridden, the version in the super class will be called, in this case it will be Object
's version.
So that's why you get ExamQuestion@143c8b3.
To fix this, put the following method in your ExamQuestion class:
public String toString() {
// return a string that means something here
}
回答2:
You should have ExamQuestion overriding toString().
回答3:
The output you are seeing is how java represents objects as strings.
The default behavior is:
this.getClass().getSimpleName() + "@" + Integer.toHexString(this.hashCode());
If you want the string representation of your object to be more clear, you should override the toString()
method in your class.
回答4:
That is the default behaviour as explained by @ValekHalfHeart in his answer.
If you want to print your objects stuff then you need to override toString
method in your class.
Say I have this code:
class MyClass{
int a,b;
}
So when I make an object of this class and pass it to println
:
public static void main(String args[]){
MyClass m = new MyClass();
m.a = 20;
m.b = 30;
System.out.println(m);
}
It will print something like MyClass@143c8b3
as is your case.
So now if I want that whenever I pass my object to println
it should print something else like values of my variables a
and b
should be printed.
Then I should override tostring
method in MyClass
:
class MyClass{
int a,b;
public String toString(){
return "MyClass values: a = "+a+" and b = "+b;
}
}
So now when I say this
public static void main(String args[]){
MyClass m = new MyClass();
m.a = 20;
m.b = 30;
System.out.println(m);
}
Its going to print MyClass values: a = 20 and b = 30
So you have to do that for your ExamQuestion
class
回答5:
All classes inherit (implicitly) from Object
, which has the toString()
method, the implementation of which is producing the output you're seeing.
To have a meaningful String representation, you must override this method to provide an implementation that's suitable for your class.
来源:https://stackoverflow.com/questions/14743784/getting-examquestion143c8b3-as-print-out-in-console