How an object will call toString method implicitly?

后端 未结 5 1112
轮回少年
轮回少年 2020-11-28 09:20

If I am printing an object of the class then it is printing the toString() method implementation even I am not writing the toString() method so wha

5条回答
  •  眼角桃花
    2020-11-28 10:09

    toString() method is present in Object class, so when u put obj in System.out.println(obj);, impliciyly it will call toString() present in Object class since every user created class will implicitly inherits Object class so as ur newly created class, that means that toString() is available in ur class so it will print something like for example: "PkgNamePackage.Classname@12cf4" However if u explicitely override toString method and give ur own implementation then it will written the string what ever u give in Overriden tostring method(); ex:

    public class DogArray {
        @Override
        public String toString() {
            return "Im the newly created Object";
        }
    
        public static void main(String args[]) {
            DogArray d1 = new DogArray();
            System.out.println(d1);
        }
    }
    
    output: Im the newly created Object
    

提交回复
热议问题