Java-Overriding toString Method

Overriding toString Method

The toString( ) method returns a string that contains a description of the object on which it is called. If you want to represent any object as a string, toString() method comes into existence. Many classes override this method. This method is automatically called when an object is output using println( ).

Program : Without Overriding toString

 

Program : With Overriding toString

Program Source : Without Overriding toString

class Data {
    
    int data1 = 20;
    int data2 = 20;
}

public class Javaapp {
    
    public static void main(String[] args){
        
        Data obj = new Data();
        System.out.println("obj : "+obj);
   }
}

Program Source : With Overriding toString

class Data {
    
    int data1 = 20;
    int data2 = 20;
    
    public String toString()
    {
        return new String("Data class contained two data.");
    }
}

public class Javaapp {
    
    public static void main(String[] args){
        
        Data obj = new Data();
        System.out.println("obj : "+obj);
   }
}

Leave a Comment