Java: @Override

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

When creating an overriding method, you may want to specify that you want to override a method in the parent class.

If you specify explicitly with @Override, the compiler can give a warning if you have made a mistake such as using a non existing method.

As shown in the example below, the fan method in line 21 will definitely override the fan method in line 7.

package overridetest;

class Music {

    int i = 1;

    int fan() {
        return i;
    }

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

class Rock extends Music {

    int i = 2;

    @Override
    int fan() {
        return i + 10;
    }

    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(Rock.groupie());
    }
}

atoverride

 

Series Navigation<< Java: Interface
Java: The final keyword >>