Rectangle 27 83

The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,

public enum MyType {
  ONE {
      public String toString() {
          return "this is one";
      }
  },

  TWO {
      public String toString() {
          return "this is two";
      }
  }
}

Running the following test code will produce this:

public class EnumTest {
  public static void main(String[] args) {
      System.out.println(MyType.ONE);
      System.out.println(MyType.TWO);
  }
}


this is one
this is two

This is not an efficient way to do this. This creates a new custom class for every value in the enumeration. In the above example, you'll see the following in the bin directory: EnumTest$MyType.class EnumTest$MyType$1.class EnumTest$MyType$2.class which will add up real quick. Best to do it as the expected answer, by passing in values to the enum constructor. I actually disagree with overriding toString(); I believe it's better to use an explicit getter such as getKey() since overriding toString() may be unexpected by another user of the enum.

totally agree with @MattQuigley . Doing so encourage users to use toString for things it should not be used for. If you need a label, you'd rather add a label attribute

Also, there is no way to go the other way around (from a string to the enum object) which is probably going to be required at some point.

overriding toString does not affect valueOf(), does it?

java - Best way to create enum of strings? - Stack Overflow

java enums
Rectangle 27 299

In Java, the equals() method that is inherited from Object is:

public boolean equals(Object other);

In other words, the parameter must be of type Object.

The ArrayList uses the correct equals method, where you were always calling the one that didn't properly override Object's equals.

Not overriding the method correctly can cause problems.

I override equals the following everytime:

@Override
public boolean equals(Object other){
    if (other == null) return false;
    if (other == this) return true;
    if (!(other instanceof MyClass))return false;
    MyClass otherMyClass = (MyClass)other;
    ...test other properties here...
}

The use of the @Override annotation can help a ton with silly mistakes.

Use it whenever you think you are overriding a super class' or interface's method. That way, if you do it wrong you will get a compile error.

This is a good argument in favour of the @Override annotation... if the OP had use @Override his compiler would have told him that he wasn't actually overriding a parent class method...

Was never aware of the @Override, thanks for that! I'd also like to add that overriding hashCode() really should have been done and may have spotted the error sooner.

Some IDEs (e.g. Eclipse) can even autogenerate equals() and hashcode() methods for you based on the class member variables.

if (!(other instanceof MyClass))return false; returns false if MyClass extends the other class. But it wouldn't return false if the other class extended MyClass. Shouldn't equal be less contradictory?

When using instanceof the previous nullcheck is redundant.

Overriding the java equals() method quirk - Stack Overflow

java equals override
Rectangle 27 292

In Java, the equals() method that is inherited from Object is:

public boolean equals(Object other);

In other words, the parameter must be of type Object.

The ArrayList uses the correct equals method, where you were always calling the one that didn't properly override Object's equals.

Not overriding the method correctly can cause problems.

I override equals the following everytime:

@Override
public boolean equals(Object other){
    if (other == null) return false;
    if (other == this) return true;
    if (!(other instanceof MyClass))return false;
    MyClass otherMyClass = (MyClass)other;
    ...test other properties here...
}

The use of the @Override annotation can help a ton with silly mistakes.

Use it whenever you think you are overriding a super class' or interface's method. That way, if you do it wrong you will get a compile error.

This is a good argument in favour of the @Override annotation... if the OP had use @Override his compiler would have told him that he wasn't actually overriding a parent class method...

Was never aware of the @Override, thanks for that! I'd also like to add that overriding hashCode() really should have been done and may have spotted the error sooner.

Some IDEs (e.g. Eclipse) can even autogenerate equals() and hashcode() methods for you based on the class member variables.

if (!(other instanceof MyClass))return false; returns false if MyClass extends the other class. But it wouldn't return false if the other class extended MyClass. Shouldn't equal be less contradictory?

When using instanceof the previous nullcheck is redundant.

Overriding the java equals() method quirk - Stack Overflow

java equals override
Rectangle 27 1324

Eclipse is defaulting to Java 1.5 and you have classes implementing interface methods (which in Java 1.6 can be annotated with @Override, but in Java 1.5 can only be applied to methods overriding a superclass method).

Go to your project/IDE preferences and set the Java compiler level to 1.6 and also make sure you select JRE 1.6 to execute your program from Eclipse.

My project was set to 1.6, so I shot for the stars and set it to 1.5, rebuilt, then back to 1.6. Miraculously this resolved my issue. Thanks for pointing me in the right direction!

having the same issue...tried the suggestion given in this answer but still not successful. :( :(

@MichaelKrauklis I'm 1.6 and I'm having this issue. I've set to 1.5 and cleaned it and set back to 1.6 and cleaned it again. Still not resolved. Any ideas?

Same problem here, in my case, I had not installed JDK 1.6, only the latest 1.7, which apparently doesn't work with Android. Installing the older 1.6 and then following these instructions, should work :)

It should be mentioned (like in the comments to the other answers) a clean build followed by a restart is often required.

java - 'Must Override a Superclass Method' Errors after importing a pr...

java android eclipse override superclass
Rectangle 27 2

Though operator overriding is a nice solution, I'm comfortable with something simpler like the following, (which also seems more likely to Java) :

char* MyClass::toString() {
    char* s = new char[MAX_STR_LEN];
    sprintf_s(s, MAX_STR_LEN, 
             "Value of var1=%d \nValue of var2=%d\n",
              var1, var2);
    return s;
}
std::cout << myClassInst;
printf("myClassInst = %s\n", myClassInst.toString() ) ;
std::cout << myClassInst.toString() ;

toString override in C++ - Stack Overflow

c++ tostring
Rectangle 27 66

You can't override a private method, but you can introduce one in a derived class without a problem. This compiles fine:

class Base
{
   private void foo()
   {
   }
}

class Child extends Base
{
    private void foo()
    {
    }
}

Note that if you try to apply the @Override annotation to Child.foo() you'll get a compile-time error. So long as you have your compiler/IDE set to give you warnings or errors if you're missing an @Override annotation, all should be well. Admittedly I prefer the C# approach of override being a keyword, but it was obviously too late to do that in Java.

As for C#'s handling of "overriding" a private method - a private method can't be virtual in the first place, but you can certainly introduce a new private method with the same name as a private method in the base class.

As I understand this, you'll only get an error if you insist on putting an @override annotation on the method in your child class.

(+1), though I don't fancy the curly-bracket-on-new-line

your answer reminds me the answers of stackoverflow.com/questions/1953530/ -- most answers just assert the facts "no you can't" and explain what you can do to workaround these facts, but they don't really try to answer the question "why it's decided like this?"

@Gregory: I don't see why. In this case I'm correcting the OP's misunderstanding - he thought you couldn't do something which in fact you can, which means there's no "why" to answer.

It should be noted that if there's a method Base.boo() which calls foo(), then it's going to be calling Base.foo() instead of Child.foo()

inheritance - Overriding private methods in Java - Stack Overflow

java inheritance private-methods
Rectangle 27 121

It's a hint for the compiler to let it know that you're overriding the method of a parent class (or interface in Java 6).

If the compiler detects that there IS no function to override, it will warn you (or error).

This is extremely useful to quickly identify typos or API changes. Say you're trying to override your parent class' method harvest() but spell it harvset(), your program will silently call the base class, and without @Override, you wouldn't have any warning about that.

Likewise, if you're using a library, and in version 2 of the library, harvest() has been modified to take an integer parameter, you would no longer override it. Again, @Override would quickly tell you.

Note that @Override only works for public and protected functions.

It should also be mentioned that multiple annotations are also possible and that other code can also be added using this. For example, when checking permissions in Android M apps, as is done in the PermissionsDispatcher.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - What does @Override mean? - Stack Overflow

java annotations override
Rectangle 27 121

It's a hint for the compiler to let it know that you're overriding the method of a parent class (or interface in Java 6).

If the compiler detects that there IS no function to override, it will warn you (or error).

This is extremely useful to quickly identify typos or API changes. Say you're trying to override your parent class' method harvest() but spell it harvset(), your program will silently call the base class, and without @Override, you wouldn't have any warning about that.

Likewise, if you're using a library, and in version 2 of the library, harvest() has been modified to take an integer parameter, you would no longer override it. Again, @Override would quickly tell you.

Note that @Override only works for public and protected functions.

It should also be mentioned that multiple annotations are also possible and that other code can also be added using this. For example, when checking permissions in Android M apps, as is done in the PermissionsDispatcher.

java - What does @Override mean? - Stack Overflow

java annotations override
Rectangle 27 22

There are two methods in super class as java.lang.Object. We need to override them to custom object.

public boolean equals(Object obj)
public int hashCode()

Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

public class Test
{
    private int num;
    private String data;
    public boolean equals(Object obj)
    {
        if(this == obj)
            return true;
        if((obj == null) || (obj.getClass() != this.getClass()))
            return false;
        // object must be Test at this point
        Test test = (Test)obj;
        return num == test.num &&
        (data == test.data || (data != null && data.equals(test.data)));
    }

    public int hashCode()
    {
        int hash = 7;
        hash = 31 * hash + num;
        hash = 31 * hash + (null == data ? 0 : data.hashCode());
        return hash;
    }

    // other methods
}

override - What issues should be considered when overriding equals and...

java override equals hashcode
Rectangle 27 36

Calling with an object instance

Here is some code which illustrates the current state of affairs in Java:

Base.java
Child.java
package sp.trial;
public class Child extends Base {
  static void printValue() {
    System.out.println("  Called static Child method.");
  }
  void nonStatPrintValue() {
    System.out.println("  Called non-static Child method.");
  }
  void localIndirectStatMethod() {
    System.out.println("  Non-static calls own static:");
    System.out.print("  ");
    printValue();
  }
  public static void main(String[] args) {
    System.out.println("Object: static type Base; runtime type Child:");
    Base base = new Child();
    base.printValue();
    base.nonStatPrintValue();
    System.out.println("Object: static type Child; runtime type Child:");
    Child child = new Child();
    child.printValue();
    child.nonStatPrintValue();
    System.out.println("Class: Child static call:");
    Child.printValue();
    System.out.println("Class: Base static call:");
    Base.printValue();
    System.out.println("Object: static/runtime type Child -- call static from non-static method of Child:");
    child.localIndirectStatMethod();
    System.out.println("Object: static/runtime type Child -- call static from non-static method of Base:");
    child.nonLocalIndirectStatMethod();
  }
}

If you run this (I did it on a Mac, from Eclipse, using Java 1.6) you get:

Object: static type Base; runtime type Child.
  Called static Base method.
  Called non-static Child method.
Object: static type Child; runtime type Child.
  Called static Child method.
  Called non-static Child method.
Class: Child static call.
  Called static Child method.
Class: Base static call.
  Called static Base method.
Object: static/runtime type Child -- call static from non-static method of Child.
  Non-static calls own static.
    Called static Child method.
Object: static/runtime type Child -- call static from non-static method of Base.
  Non-static calls overridden(?) static.
    Called static Base method.

Here, the only cases which might be a surprise (and which the question is about) appear to be the first case:

"The run-time type is not used to determine which static methods are called, even when called with an object instance (obj.staticMethod())."

and the last case:

"When calling a static method from within an object method of a class, the static method chosen is the one accessible from the class itself and not from the class defining the run-time type of the object."

The static call is resolved at compile-time, whereas a non-static method call is resolved at run-time. Notice that although static methods are inherited (from parent) they are not overridden (by child). This could be a surprise if you expected otherwise.

Object method calls are resolved using the run-time type, but static (class) method calls are resolved using the compile-time (declared) type.

To change these rules, so that the last call in the example called Child.printValue(), static calls would have to be provided with a type at run-time, rather than the compiler resolving the call at compile-time with the declared class of the object (or context). Static calls could then use the (dynamic) type hierarchy to resolve the call, just as object method calls do today.

This would easily be doable (if we changed Java :-O), and is not at all unreasonable, however, it has some interesting considerations.

The main consideration is that we need to decide which static method calls should do this.

At the moment, Java has this "quirk" in the language whereby obj.staticMethod() calls are replaced by ObjectClass.staticMethod() calls (normally with a warning). [Note: ObjectClass is the compile-time type of obj.] These would be good candidates for overriding in this way, taking the run-time type of obj.

If we did it would make method bodies harder to read: static calls in a parent class could potentially be dynamically "re-routed". To avoid this we would have to call the static method with a class name -- and this makes the calls more obviously resolved with the compile-time type hierarchy (as now).

The other ways of invoking a static method are more tricky: this.staticMethod() should mean the same as obj.staticMethod(), taking the run-time type of this. However, this might cause some headaches with existing programs, which call (apparently local) static methods without decoration (which is arguably equivalent to this.method()).

So what about unadorned calls staticMethod()? I suggest they do the same as today, and use the local class context to decide what to do. Otherwise great confusion would ensue. Of course it means that method() would mean this.method() if method was a non-static method, and ThisClass.method() if method were a static method. This is another source of confusion.

If we changed this behaviour (and made static calls potentially dynamically non-local), we would probably want to revisit the meaning of final, private and protected as qualifiers on static methods of a class. We would then all have to get used to the fact that private static and public final methods are not overridden, and can therefore be safely resolved at compile-time, and are "safe" to read as local references.

"If we did it would make method bodies harder to read: static calls in a parent class could potentially be dynamically "re-routed"." True, but this is exactly what happens with ordinary non-static function calls now. This is routinely touted as a positive feature for ordinary virtual functions, not a problem.

Why doesn't Java allow overriding of static methods? - Stack Overflow

java static override static-methods
Rectangle 27 36

Calling with an object instance

Here is some code which illustrates the current state of affairs in Java:

Base.java
Child.java
package sp.trial;
public class Child extends Base {
  static void printValue() {
    System.out.println("  Called static Child method.");
  }
  void nonStatPrintValue() {
    System.out.println("  Called non-static Child method.");
  }
  void localIndirectStatMethod() {
    System.out.println("  Non-static calls own static:");
    System.out.print("  ");
    printValue();
  }
  public static void main(String[] args) {
    System.out.println("Object: static type Base; runtime type Child:");
    Base base = new Child();
    base.printValue();
    base.nonStatPrintValue();
    System.out.println("Object: static type Child; runtime type Child:");
    Child child = new Child();
    child.printValue();
    child.nonStatPrintValue();
    System.out.println("Class: Child static call:");
    Child.printValue();
    System.out.println("Class: Base static call:");
    Base.printValue();
    System.out.println("Object: static/runtime type Child -- call static from non-static method of Child:");
    child.localIndirectStatMethod();
    System.out.println("Object: static/runtime type Child -- call static from non-static method of Base:");
    child.nonLocalIndirectStatMethod();
  }
}

If you run this (I did it on a Mac, from Eclipse, using Java 1.6) you get:

Object: static type Base; runtime type Child.
  Called static Base method.
  Called non-static Child method.
Object: static type Child; runtime type Child.
  Called static Child method.
  Called non-static Child method.
Class: Child static call.
  Called static Child method.
Class: Base static call.
  Called static Base method.
Object: static/runtime type Child -- call static from non-static method of Child.
  Non-static calls own static.
    Called static Child method.
Object: static/runtime type Child -- call static from non-static method of Base.
  Non-static calls overridden(?) static.
    Called static Base method.

Here, the only cases which might be a surprise (and which the question is about) appear to be the first case:

"The run-time type is not used to determine which static methods are called, even when called with an object instance (obj.staticMethod())."

and the last case:

"When calling a static method from within an object method of a class, the static method chosen is the one accessible from the class itself and not from the class defining the run-time type of the object."

The static call is resolved at compile-time, whereas a non-static method call is resolved at run-time. Notice that although static methods are inherited (from parent) they are not overridden (by child). This could be a surprise if you expected otherwise.

Object method calls are resolved using the run-time type, but static (class) method calls are resolved using the compile-time (declared) type.

To change these rules, so that the last call in the example called Child.printValue(), static calls would have to be provided with a type at run-time, rather than the compiler resolving the call at compile-time with the declared class of the object (or context). Static calls could then use the (dynamic) type hierarchy to resolve the call, just as object method calls do today.

This would easily be doable (if we changed Java :-O), and is not at all unreasonable, however, it has some interesting considerations.

The main consideration is that we need to decide which static method calls should do this.

At the moment, Java has this "quirk" in the language whereby obj.staticMethod() calls are replaced by ObjectClass.staticMethod() calls (normally with a warning). [Note: ObjectClass is the compile-time type of obj.] These would be good candidates for overriding in this way, taking the run-time type of obj.

If we did it would make method bodies harder to read: static calls in a parent class could potentially be dynamically "re-routed". To avoid this we would have to call the static method with a class name -- and this makes the calls more obviously resolved with the compile-time type hierarchy (as now).

The other ways of invoking a static method are more tricky: this.staticMethod() should mean the same as obj.staticMethod(), taking the run-time type of this. However, this might cause some headaches with existing programs, which call (apparently local) static methods without decoration (which is arguably equivalent to this.method()).

So what about unadorned calls staticMethod()? I suggest they do the same as today, and use the local class context to decide what to do. Otherwise great confusion would ensue. Of course it means that method() would mean this.method() if method was a non-static method, and ThisClass.method() if method were a static method. This is another source of confusion.

If we changed this behaviour (and made static calls potentially dynamically non-local), we would probably want to revisit the meaning of final, private and protected as qualifiers on static methods of a class. We would then all have to get used to the fact that private static and public final methods are not overridden, and can therefore be safely resolved at compile-time, and are "safe" to read as local references.

"If we did it would make method bodies harder to read: static calls in a parent class could potentially be dynamically "re-routed"." True, but this is exactly what happens with ordinary non-static function calls now. This is routinely touted as a positive feature for ordinary virtual functions, not a problem.

Why doesn't Java allow overriding of static methods? - Stack Overflow

java static override static-methods
Rectangle 27 36

Calling with an object instance

Here is some code which illustrates the current state of affairs in Java:

Base.java
Child.java
package sp.trial;
public class Child extends Base {
  static void printValue() {
    System.out.println("  Called static Child method.");
  }
  void nonStatPrintValue() {
    System.out.println("  Called non-static Child method.");
  }
  void localIndirectStatMethod() {
    System.out.println("  Non-static calls own static:");
    System.out.print("  ");
    printValue();
  }
  public static void main(String[] args) {
    System.out.println("Object: static type Base; runtime type Child:");
    Base base = new Child();
    base.printValue();
    base.nonStatPrintValue();
    System.out.println("Object: static type Child; runtime type Child:");
    Child child = new Child();
    child.printValue();
    child.nonStatPrintValue();
    System.out.println("Class: Child static call:");
    Child.printValue();
    System.out.println("Class: Base static call:");
    Base.printValue();
    System.out.println("Object: static/runtime type Child -- call static from non-static method of Child:");
    child.localIndirectStatMethod();
    System.out.println("Object: static/runtime type Child -- call static from non-static method of Base:");
    child.nonLocalIndirectStatMethod();
  }
}

If you run this (I did it on a Mac, from Eclipse, using Java 1.6) you get:

Object: static type Base; runtime type Child.
  Called static Base method.
  Called non-static Child method.
Object: static type Child; runtime type Child.
  Called static Child method.
  Called non-static Child method.
Class: Child static call.
  Called static Child method.
Class: Base static call.
  Called static Base method.
Object: static/runtime type Child -- call static from non-static method of Child.
  Non-static calls own static.
    Called static Child method.
Object: static/runtime type Child -- call static from non-static method of Base.
  Non-static calls overridden(?) static.
    Called static Base method.

Here, the only cases which might be a surprise (and which the question is about) appear to be the first case:

"The run-time type is not used to determine which static methods are called, even when called with an object instance (obj.staticMethod())."

and the last case:

"When calling a static method from within an object method of a class, the static method chosen is the one accessible from the class itself and not from the class defining the run-time type of the object."

The static call is resolved at compile-time, whereas a non-static method call is resolved at run-time. Notice that although static methods are inherited (from parent) they are not overridden (by child). This could be a surprise if you expected otherwise.

Object method calls are resolved using the run-time type, but static (class) method calls are resolved using the compile-time (declared) type.

To change these rules, so that the last call in the example called Child.printValue(), static calls would have to be provided with a type at run-time, rather than the compiler resolving the call at compile-time with the declared class of the object (or context). Static calls could then use the (dynamic) type hierarchy to resolve the call, just as object method calls do today.

This would easily be doable (if we changed Java :-O), and is not at all unreasonable, however, it has some interesting considerations.

The main consideration is that we need to decide which static method calls should do this.

At the moment, Java has this "quirk" in the language whereby obj.staticMethod() calls are replaced by ObjectClass.staticMethod() calls (normally with a warning). [Note: ObjectClass is the compile-time type of obj.] These would be good candidates for overriding in this way, taking the run-time type of obj.

If we did it would make method bodies harder to read: static calls in a parent class could potentially be dynamically "re-routed". To avoid this we would have to call the static method with a class name -- and this makes the calls more obviously resolved with the compile-time type hierarchy (as now).

The other ways of invoking a static method are more tricky: this.staticMethod() should mean the same as obj.staticMethod(), taking the run-time type of this. However, this might cause some headaches with existing programs, which call (apparently local) static methods without decoration (which is arguably equivalent to this.method()).

So what about unadorned calls staticMethod()? I suggest they do the same as today, and use the local class context to decide what to do. Otherwise great confusion would ensue. Of course it means that method() would mean this.method() if method was a non-static method, and ThisClass.method() if method were a static method. This is another source of confusion.

If we changed this behaviour (and made static calls potentially dynamically non-local), we would probably want to revisit the meaning of final, private and protected as qualifiers on static methods of a class. We would then all have to get used to the fact that private static and public final methods are not overridden, and can therefore be safely resolved at compile-time, and are "safe" to read as local references.

"If we did it would make method bodies harder to read: static calls in a parent class could potentially be dynamically "re-routed"." True, but this is exactly what happens with ordinary non-static function calls now. This is routinely touted as a positive feature for ordinary virtual functions, not a problem.

Why doesn't Java allow overriding of static methods? - Stack Overflow

java static override static-methods
Rectangle 27 36

Calling with an object instance

Here is some code which illustrates the current state of affairs in Java:

Base.java
Child.java
package sp.trial;
public class Child extends Base {
  static void printValue() {
    System.out.println("  Called static Child method.");
  }
  void nonStatPrintValue() {
    System.out.println("  Called non-static Child method.");
  }
  void localIndirectStatMethod() {
    System.out.println("  Non-static calls own static:");
    System.out.print("  ");
    printValue();
  }
  public static void main(String[] args) {
    System.out.println("Object: static type Base; runtime type Child:");
    Base base = new Child();
    base.printValue();
    base.nonStatPrintValue();
    System.out.println("Object: static type Child; runtime type Child:");
    Child child = new Child();
    child.printValue();
    child.nonStatPrintValue();
    System.out.println("Class: Child static call:");
    Child.printValue();
    System.out.println("Class: Base static call:");
    Base.printValue();
    System.out.println("Object: static/runtime type Child -- call static from non-static method of Child:");
    child.localIndirectStatMethod();
    System.out.println("Object: static/runtime type Child -- call static from non-static method of Base:");
    child.nonLocalIndirectStatMethod();
  }
}

If you run this (I did it on a Mac, from Eclipse, using Java 1.6) you get:

Object: static type Base; runtime type Child.
  Called static Base method.
  Called non-static Child method.
Object: static type Child; runtime type Child.
  Called static Child method.
  Called non-static Child method.
Class: Child static call.
  Called static Child method.
Class: Base static call.
  Called static Base method.
Object: static/runtime type Child -- call static from non-static method of Child.
  Non-static calls own static.
    Called static Child method.
Object: static/runtime type Child -- call static from non-static method of Base.
  Non-static calls overridden(?) static.
    Called static Base method.

Here, the only cases which might be a surprise (and which the question is about) appear to be the first case:

"The run-time type is not used to determine which static methods are called, even when called with an object instance (obj.staticMethod())."

and the last case:

"When calling a static method from within an object method of a class, the static method chosen is the one accessible from the class itself and not from the class defining the run-time type of the object."

The static call is resolved at compile-time, whereas a non-static method call is resolved at run-time. Notice that although static methods are inherited (from parent) they are not overridden (by child). This could be a surprise if you expected otherwise.

Object method calls are resolved using the run-time type, but static (class) method calls are resolved using the compile-time (declared) type.

To change these rules, so that the last call in the example called Child.printValue(), static calls would have to be provided with a type at run-time, rather than the compiler resolving the call at compile-time with the declared class of the object (or context). Static calls could then use the (dynamic) type hierarchy to resolve the call, just as object method calls do today.

This would easily be doable (if we changed Java :-O), and is not at all unreasonable, however, it has some interesting considerations.

The main consideration is that we need to decide which static method calls should do this.

At the moment, Java has this "quirk" in the language whereby obj.staticMethod() calls are replaced by ObjectClass.staticMethod() calls (normally with a warning). [Note: ObjectClass is the compile-time type of obj.] These would be good candidates for overriding in this way, taking the run-time type of obj.

If we did it would make method bodies harder to read: static calls in a parent class could potentially be dynamically "re-routed". To avoid this we would have to call the static method with a class name -- and this makes the calls more obviously resolved with the compile-time type hierarchy (as now).

The other ways of invoking a static method are more tricky: this.staticMethod() should mean the same as obj.staticMethod(), taking the run-time type of this. However, this might cause some headaches with existing programs, which call (apparently local) static methods without decoration (which is arguably equivalent to this.method()).

So what about unadorned calls staticMethod()? I suggest they do the same as today, and use the local class context to decide what to do. Otherwise great confusion would ensue. Of course it means that method() would mean this.method() if method was a non-static method, and ThisClass.method() if method were a static method. This is another source of confusion.

If we changed this behaviour (and made static calls potentially dynamically non-local), we would probably want to revisit the meaning of final, private and protected as qualifiers on static methods of a class. We would then all have to get used to the fact that private static and public final methods are not overridden, and can therefore be safely resolved at compile-time, and are "safe" to read as local references.

"If we did it would make method bodies harder to read: static calls in a parent class could potentially be dynamically "re-routed"." True, but this is exactly what happens with ordinary non-static function calls now. This is routinely touted as a positive feature for ordinary virtual functions, not a problem.

Why doesn't Java allow overriding of static methods? - Stack Overflow

java static override static-methods
Rectangle 27 22

Actually we were wrong. Despite Java doesn't allow you to override static methods by default, if you look thoroughly through documentation of Class and Method classes in Java, you can still find a way to emulate static methods overriding by following workaround:

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;

class RegularEmployee {

    private BigDecimal salary = BigDecimal.ONE;

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }
    public static BigDecimal getBonusMultiplier() {
        return new BigDecimal(".02");
    }
    public BigDecimal calculateBonus() {
        return salary.multiply(this.getBonusMultiplier());
    }
    public BigDecimal calculateOverridenBonus() {
        try {
            // System.out.println(this.getClass().getDeclaredMethod(
            // "getBonusMultiplier").toString());
            try {
                return salary.multiply((BigDecimal) this.getClass()
                    .getDeclaredMethod("getBonusMultiplier").invoke(this));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return null;
    }
    // ... presumably lots of other code ...
}

final class SpecialEmployee extends RegularEmployee {

    public static BigDecimal getBonusMultiplier() {
        return new BigDecimal(".03");
    }
}

public class StaticTestCoolMain {

    static public void main(String[] args) {
        RegularEmployee Alan = new RegularEmployee();
        System.out.println(Alan.calculateBonus());
        System.out.println(Alan.calculateOverridenBonus());
        SpecialEmployee Bob = new SpecialEmployee();
        System.out.println(Bob.calculateBonus());
        System.out.println(Bob.calculateOverridenBonus());
    }
}
0.02
0.02
0.02
0.03

Even if we declare third variable Carl as RegularEmployee and assign to it instance of SpecialEmployee, we will still have call of RegularEmployee method in first case and call of SpecialEmployee method in second case

RegularEmployee Carl = new SpecialEmployee();

System.out.println(Carl.calculateBonus());
System.out.println(Carl.calculateOverridenBonus());
0.02
0.03

Yes reflection is pretty much the only thing one can do - but the question is not exactly this - useful to have it here though

Nice hack but it's unlikely that anyone would use this in actual production....

Why doesn't Java allow overriding of static methods? - Stack Overflow

java static override static-methods
Rectangle 27 21

Actually we were wrong. Despite Java doesn't allow you to override static methods by default, if you look thoroughly through documentation of Class and Method classes in Java, you can still find a way to emulate static methods overriding by following workaround:

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;

class RegularEmployee {

    private BigDecimal salary = BigDecimal.ONE;

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }
    public static BigDecimal getBonusMultiplier() {
        return new BigDecimal(".02");
    }
    public BigDecimal calculateBonus() {
        return salary.multiply(this.getBonusMultiplier());
    }
    public BigDecimal calculateOverridenBonus() {
        try {
            // System.out.println(this.getClass().getDeclaredMethod(
            // "getBonusMultiplier").toString());
            try {
                return salary.multiply((BigDecimal) this.getClass()
                    .getDeclaredMethod("getBonusMultiplier").invoke(this));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return null;
    }
    // ... presumably lots of other code ...
}

final class SpecialEmployee extends RegularEmployee {

    public static BigDecimal getBonusMultiplier() {
        return new BigDecimal(".03");
    }
}

public class StaticTestCoolMain {

    static public void main(String[] args) {
        RegularEmployee Alan = new RegularEmployee();
        System.out.println(Alan.calculateBonus());
        System.out.println(Alan.calculateOverridenBonus());
        SpecialEmployee Bob = new SpecialEmployee();
        System.out.println(Bob.calculateBonus());
        System.out.println(Bob.calculateOverridenBonus());
    }
}
0.02
0.02
0.02
0.03

Even if we declare third variable Carl as RegularEmployee and assign to it instance of SpecialEmployee, we will still have call of RegularEmployee method in first case and call of SpecialEmployee method in second case

RegularEmployee Carl = new SpecialEmployee();

System.out.println(Carl.calculateBonus());
System.out.println(Carl.calculateOverridenBonus());
0.02
0.03

Yes reflection is pretty much the only thing one can do - but the question is not exactly this - useful to have it here though

Nice hack but it's unlikely that anyone would use this in actual production....

Why doesn't Java allow overriding of static methods? - Stack Overflow

java static override static-methods
Rectangle 27 21

Actually we were wrong. Despite Java doesn't allow you to override static methods by default, if you look thoroughly through documentation of Class and Method classes in Java, you can still find a way to emulate static methods overriding by following workaround:

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;

class RegularEmployee {

    private BigDecimal salary = BigDecimal.ONE;

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }
    public static BigDecimal getBonusMultiplier() {
        return new BigDecimal(".02");
    }
    public BigDecimal calculateBonus() {
        return salary.multiply(this.getBonusMultiplier());
    }
    public BigDecimal calculateOverridenBonus() {
        try {
            // System.out.println(this.getClass().getDeclaredMethod(
            // "getBonusMultiplier").toString());
            try {
                return salary.multiply((BigDecimal) this.getClass()
                    .getDeclaredMethod("getBonusMultiplier").invoke(this));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return null;
    }
    // ... presumably lots of other code ...
}

final class SpecialEmployee extends RegularEmployee {

    public static BigDecimal getBonusMultiplier() {
        return new BigDecimal(".03");
    }
}

public class StaticTestCoolMain {

    static public void main(String[] args) {
        RegularEmployee Alan = new RegularEmployee();
        System.out.println(Alan.calculateBonus());
        System.out.println(Alan.calculateOverridenBonus());
        SpecialEmployee Bob = new SpecialEmployee();
        System.out.println(Bob.calculateBonus());
        System.out.println(Bob.calculateOverridenBonus());
    }
}
0.02
0.02
0.02
0.03

Even if we declare third variable Carl as RegularEmployee and assign to it instance of SpecialEmployee, we will still have call of RegularEmployee method in first case and call of SpecialEmployee method in second case

RegularEmployee Carl = new SpecialEmployee();

System.out.println(Carl.calculateBonus());
System.out.println(Carl.calculateOverridenBonus());
0.02
0.03

Yes reflection is pretty much the only thing one can do - but the question is not exactly this - useful to have it here though

Nice hack but it's unlikely that anyone would use this in actual production....

Why doesn't Java allow overriding of static methods? - Stack Overflow

java static override static-methods
Rectangle 27 21

Actually we were wrong. Despite Java doesn't allow you to override static methods by default, if you look thoroughly through documentation of Class and Method classes in Java, you can still find a way to emulate static methods overriding by following workaround:

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;

class RegularEmployee {

    private BigDecimal salary = BigDecimal.ONE;

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }
    public static BigDecimal getBonusMultiplier() {
        return new BigDecimal(".02");
    }
    public BigDecimal calculateBonus() {
        return salary.multiply(this.getBonusMultiplier());
    }
    public BigDecimal calculateOverridenBonus() {
        try {
            // System.out.println(this.getClass().getDeclaredMethod(
            // "getBonusMultiplier").toString());
            try {
                return salary.multiply((BigDecimal) this.getClass()
                    .getDeclaredMethod("getBonusMultiplier").invoke(this));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return null;
    }
    // ... presumably lots of other code ...
}

final class SpecialEmployee extends RegularEmployee {

    public static BigDecimal getBonusMultiplier() {
        return new BigDecimal(".03");
    }
}

public class StaticTestCoolMain {

    static public void main(String[] args) {
        RegularEmployee Alan = new RegularEmployee();
        System.out.println(Alan.calculateBonus());
        System.out.println(Alan.calculateOverridenBonus());
        SpecialEmployee Bob = new SpecialEmployee();
        System.out.println(Bob.calculateBonus());
        System.out.println(Bob.calculateOverridenBonus());
    }
}
0.02
0.02
0.02
0.03

Even if we declare third variable Carl as RegularEmployee and assign to it instance of SpecialEmployee, we will still have call of RegularEmployee method in first case and call of SpecialEmployee method in second case

RegularEmployee Carl = new SpecialEmployee();

System.out.println(Carl.calculateBonus());
System.out.println(Carl.calculateOverridenBonus());
0.02
0.03

Yes reflection is pretty much the only thing one can do - but the question is not exactly this - useful to have it here though

Nice hack but it's unlikely that anyone would use this in actual production....

Why doesn't Java allow overriding of static methods? - Stack Overflow

java static override static-methods
Rectangle 27 8

It's not possible to do this in Java. (The sole purpose of the final keyword when it comes to methods, is to prevent overriding!)

equals and a few other methods on Enums are final, so you can't change the behavior of them. (And you shouldn't :) Here is my answer to a related question:

The intuition of clients that deal with enum constants is that two constants are equal if and only if they are the same constant. Thus any other implementation than return this == other would be counterintuitive and error prone.

hashCode()
clone()
compareTo(Object)
name()
ordinal()
getDeclaringClass()

The JLS does not motivate the choice of making it final, but mentions equals in the context of enums here. Snippet:

The equals method in Enum is a final method that merely invokes super.equals on its argument and returns the result, thus performing an identity comparison.

How to override the (final) equals method in java enums? - Stack Overf...

java enums override equals final
Rectangle 27 8

It's not possible to do this in Java. (The sole purpose of the final keyword when it comes to methods, is to prevent overriding!)

equals and a few other methods on Enums are final, so you can't change the behavior of them. (And you shouldn't :) Here is my answer to a related question:

The intuition of clients that deal with enum constants is that two constants are equal if and only if they are the same constant. Thus any other implementation than return this == other would be counterintuitive and error prone.

hashCode()
clone()
compareTo(Object)
name()
ordinal()
getDeclaringClass()

The JLS does not motivate the choice of making it final, but mentions equals in the context of enums here. Snippet:

The equals method in Enum is a final method that merely invokes super.equals on its argument and returns the result, thus performing an identity comparison.

How to override the (final) equals method in java enums? - Stack Overf...

java enums override equals final
Rectangle 27 4

I like and double Jay's comment (https://stackoverflow.com/a/2223803/1517187). I agree that this is bad design of Java. Many other languages support overriding static methods, as we see in previous comments. I feel Jay has also come to Java from Delphi like me. Delphi (Object Pascal) was the first language implementing OOP. It is obvious that many people had experience with that language, since it was in the past the only language to write commercial GUI products. And - yes, we could in Delphi override static methods. Actually, static methods in Delphi are called "class methods", while Delphi had different concept of "Delphi static methods" which were methods with early binding. To override methods you had to use late binding, declare "virtual" directive. So it was very convenient and intuitive and I would expect this in Java.

Why doesn't Java allow overriding of static methods? - Stack Overflow

java static override static-methods