Search code examples
javaoverridingoverloadingtostring

How is the .toString() overloaded in the Arrays class


I came across the concept where a method cannot be overridden and overloaded at the same time. But when I used Arrays.toString(), image1

Correct me if I'm wrong, but the toString() method has been overridden and overloaded at the same time. How is that possible?


Solution

  • You are overriding when you have the exact same method signature in a subclass. You are overloading when you have two equal named methods with different type or number of parameters. You can override a method and then overload it but you can write a method and it can happend that when you overload it you end up overriding a super class method. One thing doesn't exclude the other.

    Let's have a Super class like this:

    public class Super {
    
        public void testMethod() {}
    
        // Overload
        public void testMethod(String param) {}
    }
    

    And then extend it with a sub class like this:

    public class Sub extends Super {
    
        // Override only
        @Override
        public void testMethod() {}
    
        // Overload only
        public void testMethod(int param) {}
    
        // Overload and Override
        @Override
        public void testMethod(String param) {}
    }
    

    As you can see, you can have only overload, only override or both in multiple ways. As said, one thing doesn't exclude the other.