Consider the following Scala program:
The output is, class name, then ‘at’ sign, and at the end hashCode of object. All classes in Scala inherit from the Object class, directly or indirectly . The object class has some basic methods like clone(), toString(), equals(), .. etc. The default toString() method in Object prints “class name @ hash code”. We can override toString() method in our class to print proper output. Below is the example to override toString method.
[Total Article : 50, Language Name = Scala]
In above example Language class, which is overriding the toString() method and returning string value. This method has attributes names and values. The class defines two variables LangArticle and LangName and three methods: getLangArticle, getLangName and toString. getLangArticle takes one integer arguments and return a value. getLangName takes one string arguments and return a value. toString, on the other hand, does take any parameters but returns a String value. Since toString overrides the pre-defined toString method, it has to be tagged with the override flag.
Note: When we override the any super class method . We should use override keyword before the method (i.e: override def toString()).