In: Computer Science
Java
public class UpperCaseString { //1 protected String content; // 2 public UpperCaseString(String content) { // 3 this.content = content.toUpperCase(); // 4 } // 5 public String toString() { // 6 return content.toUpperCase(); // 7 } // 8 public static void main(String[] args) { // 9 UpperCaseString upperString = new UpperCaseString("Hello, Cleo!"); // 10 System.out.println(upperString); // 11 } // 12 } // 13 |
THE FOLLOWING 3 QUESTIONS REFER TO THE CODE FRAGMENT ABOVE
__________________________________________________
______________________________________________________________
______________________________________________________________
Answer 1:
Display on Console: HELLO, CLEO!
Explanation: When we are creagting object upperString of UpperCaseString class, we are passing value 'HELLO, CLEO! ' So it will be stored in content of the object (using the constructor). And when we print the object it's printing its value.
Answer 2:
toString() method is being invoked in order to print to the value of the object on the console.
When we print any object, java compiler internally invokes the toString() method on the object.
In Java, all classes inherit from the Object class. And toString() is the method of object class. toString() method in Object prints “class name @ hash code”. But here we have override toString() method. So when we print object it will print the value accordingly.
Answer 3:
protected access modifier makes attribute accessible in the same package and subclasses. So to prevent further access content is made protected.