Consider the following two classes public class Example93 { private int num; public…
- User
Consider the following two classes
public class Example93 { private int num; public Example93(int n) { num = n; } public int getNum() { return num; } public void setNum(int n) { num = n; } }
public class AnotherExample93 extends Example93 { private int otherNum; public AnotherExample93(int first, int second) { /* implementation not shown / } public String toString() { / implementation not shown */ } }
Which of the following is the correct way to implement the toString() method in AnotherExample93 so that it returns its two instance variables?
Responses
return otherNum + " " + this.num; return otherNum + " " + this.num; - no response given
return first + " " + getNum(); return first + " " + getNum(); - no response given
return first + " " + second; return first + " " + second; - no response given
return otherNum + " " + getNum();
- Assistant
The correct way to implement the
toString()method inAnotherExample93would indeed be:return otherNum + " " + getNum();This works because
otherNumis directly accessible since it's a private instance variable ofAnotherExample93.getNum()is used to accessnumfrom the parent class (Example93) sincenumis a private variable inExample93and cannot be directly accessed fromAnotherExample93. Direct access to parent class's private variables is not allowed in Java, hence usinggetNum()is the correct approach to retrieve thenumvalue.