2.8k views
5 votes
You have written a class called Frog and have not written a toString method. Frog f = new Frog(); System.out.println(f); What happens when the code above is executed? "Ribbit" is printed. Error - a class cannot be instantiated without the toString method. Error - Frog has no toString method. Nothing happens. The toString method in Object is called.

User Ben Carp
by
8.0k points

2 Answers

4 votes

Answer:

The toString method in Object is called.

Step-by-step explanation:

toString method in a class is a special method that will be invoked when we try to use println() method to display the value of a class instance. toString method is usually used to show the current state of attribute in a class instance.

However, if there is no toString method defined in a class, the toString method in the parent class will be called. In Java, all classes are inherited from Object class and therefore the Object class is a parent class and its toString method will be invoked if the toString method is missing from its child class.

User Chiguireitor
by
7.8k points
4 votes
The correct answer is: 'The toString method in Object is called.' If you don't explicitly write a ToString() method in your class, the ToString() method in the parent class is called. Your own 'ToString()' method would overload the parent Object 'ToString()' method.
User Felesha
by
8.2k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.