Java: Overriding superclass method

This entry is part 44 of 54 in the series Learn Java

When a class defines an instance method using the same name, return type, and parameters as a method in its superclass, that method overrides the method of the superclass.

When the method is invoked for an object of the class, it is the new definition of the method that is called, not the old definition from the superclass.

package overridetest;

class Music {                          

    int i = 1;                       

    int fan() {
        return i;
    }            

    static String groupie() {
        return "Music";
    }
}

class Rock extends Music {                

    int i = 2;                       

    int fan() {
        return -i;
    }           

    static String groupie() {
        return "Rock";
    }
}

public class OverrideTest {

    public static void main(String args[]) {
        Rock r = new Rock();               
        System.out.println(r.i);     
        System.out.println(r.fan());   
        System.out.println(r.groupie());   
        System.out.println(Rock.groupie());   

        Music m = (Music) r;                 
        System.out.println(m.i);     
        System.out.println(m.fan());   
        System.out.println(m.groupie());   
        System.out.println(Music.groupie());   
    }
}

Notice that when we defined a method as static, such as groupie method above, we can access the method using r.groupie() or Rock.groupie().

override

 

Series Navigation<< Java: Adding a class in a separate file
Java: Access to classes and members >>