Search code examples
javamethodsstaticoverloadingencapsulation

overloading and hiding - differences


I prepare for SCJP and I have a bit confusing with this terms from jls.

about overloading from jls:

If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

about hiding:

If a class C declares or inherits a static method m, then m is said to hide any method m', where the signature of m is a subsignature (§8.4.2) of the signature of m', in the superclasses and superinterfaces of C that would otherwise be accessible to code in C.

looks like hiding is part of overloading for static methods only.

But these definitions are quite ornate. please clarify difference.

Can you provide concrete examples which allow to feel the difference?


Solution

  • Overloading is when you have 2 or more methods with the same name, but with different parameters. http://en.wikipedia.org/wiki/Method_overloading

    Overriding is when the methods are not static and the names and parameters are the same.

    For example,

    public class A {
       public void test1(String a) {System.out.println(a);}
    }
    
    public class B extends A {
       public void test1(String a) {System.out.println(a);}
    }
    

    Then you are overriding the method test1.

    Hiding only happens if both methods are static.

    The distinction between hiding a static method and overriding an instance method has important implications:

    The version of the overridden instance method that gets invoked is the one in the subclass. The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.

    From http://docs.oracle.com/javase/tutorial/java/IandI/override.html