Java - Reimplementing toString() Method of the Object Class in the SmartInt Class

Requirement

Following the steps listed below to create your own class

  • Create a class named SmartInt
  • Add one private field named value, whose type is int,
  • Add getter and setter for value
  • Reimplementing toString() Method to use the value of int

Test Case

SmartInt intHolder = new SmartInt(234);
String intHolderStr = intHolder.toString();
System.out.println(intHolderStr);
    

The code above should output 234, which is the int value stored in value field.

Demo

class SmartInt {
  private int value;

  public SmartInt(int value) {
    this.value = value;
  }/*  ww w.ja  v a 2  s  . c  o  m*/

  public void setValue(int value) {
    this.value = value;
  }

  public int getValue() {
    return value;
  }

  /* Re implement toString() method of the Object class */
  public String toString() {
    // Return the stored value as a string
    String str = String.valueOf(this.value);
    return str;
  }
}

public class Main {
  public static void main(String[] args) {
    // Create an object of the SmartInt class
    SmartInt intHolder = new SmartInt(234);
    String intHolderStr = intHolder.toString();
    System.out.println(intHolderStr);

    // Change the value in SmartInt object
    intHolder.setValue(1234);
    intHolderStr = intHolder.toString();
    System.out.println(intHolderStr);
  }
}

Result

Related Topic