1

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
John Pham
  • 57
  • 5
  • Change `funcOne` in the first test and you'll see. `@Override` throws an error if the function *does not* override another function. – markspace Oct 19 '22 at 04:11
  • 1
    Note that `@Override` is not a _keyword_. It is an _annotation_. If you place it on a method, then the compiler will check to make sure the method actually overrides something, throwing an error if it does not. And static methods can never override anything. In the static case, your `Test.funcOne` static method _hides_ the `one.funcOne` static method but does not _override_ it. – Slaw Oct 19 '22 at 04:38
  • Ah, so the annotation @Override is for making sure this method as overridden something. Thank you guys for your help! – John Pham Oct 21 '22 at 02:44

2 Answers2

2

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.)

Cary Zheng
  • 95
  • 7
0

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413