Home > Net >  Keyword "@Override" and static methods in Java
Keyword "@Override" and static methods in Java

Time:10-19

I am learning about the concept interface in Java, specifically about its inheritance with class. From what I understood, this is a basic code syntax for an interface inheritance

interface one{
    void funcOne();
}

class Test implements one{
    @Override public void funcOne(){
         System.out.println("this is one");  
    }
}

But when I removed the phrase @Override, the code still worked fine. So what is the purpose of using that keyword?

  • My confusion adds up when testing with static methods. For instance the code below would throw an error
interface one{
    static void funcOne(){
        System.out.println("hello");
    }
}

class Test implements one{
    @Override static void funcOne() {
        System.out.println("This is one");
    }
}

But it would not throw an error when @Override is removed.

When should I use the keyword @Override, and what does it have to do with static functions?

Thank you in advance.

CodePudding user response:

Using annotation @Override to let your compiler help you check if it actually overrides a method.

In case like

public String tostring() {
    return ...;
}

You might mistake "tostring()" from "toString()", and you thought you overrode it correctly. The code would be compiled and run just like normal, but the result when method toString() was called cannot be what you wished for.

But if you used the annotation @Override

@Override
public String tostring() {
    return ...;
}

When you tried to compile it, the compiler would show you an error to clarify that you did not override any method. Then you would find out that you did not spell it right.

2. Static method cannot be overridden, it can only be hidden.

(Accept if it helps you, thx.)

CodePudding user response:

It's not required but highly recommended. This thread should clarify your question: When do you use Java's @Override annotation and why?

CodePudding user response:

Overriding isn't really a thing with static methods. You never need to use it on static methods, and you never should use it on static methods.

  • Related