Simon
Simon

Reputation: 80879

Why can I not have an abstract and static method in the same class in Java

I have the following class:

public abstract class A
{
  public abstract String doSomething(String X, String Y);
  public static String doSomething(String X, String Y){return X + Y;}
  ...
}

The issue I have is that the static and abstract doSomething() methods seem to clash as duplicates. I thought this should be fine because the static method belongs to the class, not an instance of the class, so I was going to use the abstract method to enforce the method on all subclasses and the static method as a helper so that I have nicely factored code.

I know I could probably add an interface into the mix, but I don't really understand what's wrong with my abstract and static methods existing on the same class. What's wrong with this?

Upvotes: 2

Views: 518

Answers (3)

maerics
maerics

Reputation: 156632

In Java it is valid (despite being misleading and confusing) to call a static method from an object instance rather than the class name (despite warnings generated by many compilers).

System.out.println(String.valueOf(true)); // Prints "true".
System.out.println("".valueOf(true)); // Prints "true", unfortunately.

So the following seemingly valid code wouldn't know which of those methods to call:

A a = getInstanceOfConcreteSubclassOfA();
a.doSomething(null, null); // Compiler can't decide which method to call...

Unfortunately, it's just one of the few ugly corners of the Java language.

Upvotes: 8

ruakh
ruakh

Reputation: 183554

It's not specific to abstract methods; in general, Java doesn't let you have two methods with the same parameter-types but one being static and one not. Something like this:

public String doSomething(String X, String Y){return X + Y;}
public static String doSomething(String X, String Y){return X + Y;}

would also be illegal.

(This makes sense when you consider that you're allowed to call a static method "on" an actual instance, or for that matter, on any expression of the appropriate type. The compiler translates ((A)null).staticMethod() to A.staticMethod().)

Upvotes: 3

Adel Boutros
Adel Boutros

Reputation: 10295

Each method has a signature composed of:

method name
parameter type
Return type

If 2 methods have the same signature, this will cause an error.

the word static does not interfere in the signature of the method just like const.

Upvotes: 1

Related Questions