Why we Override toString() - Bug Reaper

                  Bug Reaper

Lean about Automation Testing,Selenium WebDriver,RestAssured,Appium,Jenkins,JAVA,API Automation,TestNG,Maven, Rest API, SOAP API,Linux,Maven,Security Testing,Interview Questions

Saturday, 7 March 2020

Why we Override toString()

Class without toString() Override


package EmployeeWithLowestSalaryUsingPriorityQueue;

public class Employee {
    String name;
    int salary;

    //Creating Constructor
    public Employee(String name,int salary){

        this.name=name;
        this.salary=salary;
    }


    public static void main(String[] args) {
        Employee employee=new Employee("Neeraj",400000);
        System.out.println(employee);
    }
}

Output

Employee@677327b6

Class with toString() Override

public class Employee {
    String name;
    int salary;

    //Creating Constructor
    public Employee(String name,int salary){

        this.name=name;
        this.salary=salary;
    }

    /*
    The toString() method returns the string representation of the object.
    If you print any object, java compiler internally invokes the toString() method on the object.
     So overriding the toString() method, returns the desired output, it can be the state of an object
     */
    @Override
    public String toString(){
        return name+"and "+salary;
    }

    public static void main(String[] args) {
        Employee employee=new Employee("Neeraj",400000);
        System.out.println(employee);
    }
}


Output
Neeraj and 400000


As you can see we get meaningful output when we override toString()

No comments:

Post a Comment