groupstudent
groupstudent

Reputation: 4317

What's the difference between override and hidden in java?

I searched a lot. The difference between them is that override is for the instance method and hidden is for the static method. And the hidden is in fact the redefinition of the method. But I still don't get it.If redefinition means that the static method of parent still exists in the subclass, it is just we can't see it? Or why we call it hidden but not any other words? But if it exists, I can't find a way to call the method again. To be honest from a function level I can't find why they are different. Can some one explain it from a deeper level such as memory?

Upvotes: 3

Views: 939

Answers (3)

shmosel
shmosel

Reputation: 50776

If you call Superclass.staticMethod() you will get the method as defined on the superclass, regardless of any hiding taking place in subclasses. On the other hand, if you call ((Superclass)subObj).instanceMethod() you'll still be calling the method as it is overridden in the subclass.

Upvotes: 0

Balu
Balu

Reputation: 958

Static members(methods and variables) will not be present in the sub class(Child class) object which inherit them but they'll be present as a single copy in the memory.

Static members can be accessed by the class name of both Super class and sub class but they are not physically present in the object of these classes.

Where as when you inherit non-static members, Sub class object in memory will contain both inherited methods as well as the methods of its own. So when you try to write a similar method here, super class method will be overridden. On the other hand as static methods does not participate in inheritance, any similar method you write that is present in super class, new method will run every-time it is asked for. Parent class method is just hidden but not overridden!

Upvotes: 2

merlin2011
merlin2011

Reputation: 75649

From JLS 8.4.8.2, example 8.4.8.2-1 shows us that a hidden method binds to the type of the reference (Super), while an overriden method binds to the type of Object (Sub).

class Super {
    static String greeting() { return "Goodnight"; }
    String name() { return "Richard"; }
}
class Sub extends Super {
    static String greeting() { return "Hello"; }
    String name() { return "Dick"; }
}
class Test {
    public static void main(String[] args) {
        Super s = new Sub();
        System.out.println(s.greeting() + ", " + s.name());
    }
}

Output:

Goodnight, Dick

Upvotes: 2

Related Questions