Note that there are some explanatory texts on larger screens.

plurals
  1. POOverriding vs Hiding Java - Confused
    primarykey
    data
    text
    <p>I'm confused on how Overriding differs from Hiding in Java. Can anyone provide more details on how these differ? I read the <a href="http://docs.oracle.com/javase/tutorial/java/IandI/override.html" rel="nofollow noreferrer">Java Tutorial</a> but the sample code still left me confused.</p> <p>To be more clear, I understand Overriding well. My issue is that I don't see that hiding is any different except for the fact that one is at the instance level while the other is at the class level.</p> <p>Looking at the Java tutorial code:</p> <pre><code>public class Animal { public static void testClassMethod() { System.out.println("Class" + " method in Animal."); } public void testInstanceMethod() { System.out.println("Instance " + " method in Animal."); } } </code></pre> <p>Then we have a subclass cat:</p> <pre><code>public class Cat extends Animal { public static void testClassMethod() { System.out.println("The class method" + " in Cat."); } public void testInstanceMethod() { System.out.println("The instance method" + " in Cat."); } public static void main(String[] args) { Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); myAnimal.testInstanceMethod(); } } </code></pre> <p>Then they say:</p> <blockquote> <p>The output from this program is as follows:</p> <p>Class method in Animal.</p> <p>The instance method in Cat.</p> </blockquote> <p>To me, the fact that calling a class method testClassMethod() directly from the Animal class, executes the method in Animal class is pretty obvious, nothing special there. Then they call the testInstanceMethod() from a reference to myCat, so again pretty obvious that the method executed then is the one in the instance of Cat.</p> <p>From what I see what the call hiding behaves just like overriding, so why make that distinction. If I run this code using the classes above:</p> <pre><code>Cat.testClassMethod(); </code></pre> <p>I'll get: <em>The class method in Cat.</em> But if I remove the testClassMethod() from Cat, then I'll get: <em>The class method in Animal.</em></p> <p>Which shows me that writing a static method, with the same signature as in the parent, in a subclass pretty much does an override.</p> <p>Hopefully I'm making clear my where I'm confused and someone can shed some light. Thanks very much in advance!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload