-4

I don´t know why I can not override one method but other I can for others.

Here is the method I want to override in another class (without extending the class with the method):

public static void onOk() throws Exception {
    throw new Exception("test");
}

I am trying to override but it says "Annotation not allowed here" but below the method are a lot of other methods whose get just overridden.

@Override  <- red underlined error "Annotation not allowed here"
InputAdressDialogFragment.onOk(){
}

@Override  <- works! The compiler accepts
    public View onCreateView(
GhostCat
  • 137,827
  • 25
  • 176
  • 248
abuibos
  • 1
  • 1
  • 6
    In the first example you're *calling* a method. In the second example you're *declaring* a method. Note that you can't override static methods anyway, and you *have* to extend a class to override a method from it. It's really unclear what you're trying to do, to be honest... – Jon Skeet Jul 04 '17 at 07:46
  • 3
    can you not see the different in the structure of `@Override public View onCreateView(...` and `@Override InputAdressDialogFragment.onOk(){ ` ? – Scary Wombat Jul 04 '17 at 07:46
  • 1
    You can not override `static` methods. To override some methods it must be available in its parent class and aslo not static. Here You are directly calling method name by its class reference. So It is not possible to `override` `onOk()` method – Pragnesh Ghoda シ Jul 04 '17 at 07:48
  • Just for the record: a **compiler error** is not at all the same as **an exception gets thrown**. I reworded your question about that. – GhostCat Jul 04 '17 at 07:57

2 Answers2

2

By definition, @Override is for overriding methods.

Static methods can't be overridden - see here for details.

That is one of the reasons why using static is regarded an abnormality in good OOP.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

A class Child where Child extends Parent can only override methods defined in its super class Parent which are non static.

In the static context there is no implicit reference of current object (this) as static methods do not need any object upon which to invoke like normal non static methods. Static methods are not object based but based on class.

nits.kk
  • 5,204
  • 4
  • 33
  • 55