To provide meaningful output for:
System.out.print( new Item ()):
A method with which signature should be added to the Item class?
A.
public String asString()
B.
public Object asString()
C.
public Item asString()
D.
public String toString()
E.
public object toString()
F.
public Item toString()
Explanation:
Implementing toString method in java is done by overriding the Object’s toString method. The
javatoString() method is used when we need a string representation of an object. It is defined in
Object class. Thismethod can be overridden to customize the String representation of the Object.
Note:
Below is an example shown of Overriding the default Object toString() method. The toString()
method must bedescriptive and should generally cover all the contents of the object.
class PointCoordinates {
private int x, y;
public PointCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
// Custom toString() Method.
public String toString() {
return “X=” + x + ” ” + “Y=” + y;
}}
Answer is D