Jul 2, 2012

Abstract Classes, Interfaces and Why Static Abstract Methods can't be declared?

Lets make a review:
Interfaces

  • All variables defined in an interface must be public, static, and final.
  • Interface methods must not be static.
  • Interface methods implicitly are abstract and cannot have implementations.

Abstract class

  • Unlike interfaces, abstract classes can contain fields that are not static and final.
  • abstract classes can contain implemented methods.
  • An abstract class may have static fields and static methods. You can use these static members with a class reference. 
  •  Static methods in abstract classes must be implemented.

Static Methods.

  • You can call a static method with a class reference or with an object
  • Static methods can't be overriding.
  • The calls to static methods are determined by the reference type at compile time, instead of the object type which are determined in run time
  • Polymorphism aren't supported.  You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • It is not necessary to have any instance of the class within the static method. The compiler changes the object references  for class references when calling static methods.

Given the Java Specification, a method couldn't be Abstract and Static at the same time; You can't declare static methods in interfaces or abstract classes. Nevertheless, you can implement static methods in abstract classes.

The reason to don't allow static and abstract in the same method is that,
You can call a implemented static method, but try to figure out what should happen if you call a not-implemented static method through a class reference ( by an abstract class or interface).

You can't call a static abstract method because you haven't a specific implementation at compile time.

Also you might be thinking in implement this abstract static method in a subclass and make class references  to this method through the subclass, but it is not possible given that the static methods doesn't have polymorphic behavior

References:
Interfaces and Inheritance

Static Methods in an Interface 


No comments:

Post a Comment