Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use static method in an abstract class?

In Java Programming, Can we call a static method of an abstract class?
Yes I know we can't use static with a method of an abstract class. but I want to know why.. ?

like image 962
Neha Gupta Avatar asked Jul 01 '13 14:07

Neha Gupta


People also ask

Can we have static methods in abstract class Java?

In Java, a static method cannot be abstract. Doing so will cause compilation errors.

Can abstract class have static and final methods?

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.

Why abstract and static Cannot be used together?

A static method belongs to class not to object instance thus it cannot be overridden or implemented in a child class. So there is no use of making a static method as abstract.


2 Answers

In Java you can have a static method in an abstract class:

abstract class Foo {    static void bar() { } } 

This is allowed because that method can be called directly, even if you do not have an instance of the abstract class:

Foo.bar(); 

However, for the same reason, you can't declare a static method to be abstract. Normally, the compiler can guarantee that an abstract method will have a real implementation any time that it is called, because you can't create an instance of an abstract class. But since a static method can be called directly, making it abstract would make it possible to call an undefined method.

abstract class Foo {    abstract static void bar(); }  // Calling a method with no body! Foo.bar(); 

In an interface, all methods are implicitly abstract. This is why an interface cannot declare a static method. (There's no architectural reason why an interface couldn't have a static method, but I suspect the writers of the JLS felt that that would encourage misuse of interfaces)

like image 153
Russell Zahniser Avatar answered Sep 28 '22 18:09

Russell Zahniser


If you are talking about java, answer is Yes But you need to define the static method. You cannot create an abstract static method. What you can create is non abstract static method.

Reason is you do not need a object instance to access a static method, so you need the method to be defined with a certain functionality.

so you cannot have,

  abstract class AbstractClassExample{      abstract static void method();   }   

But you can have,

abstract class AbstractClassExample{       static void method(){} }   

Hope this helps...

like image 39
Dulanga Avatar answered Sep 28 '22 18:09

Dulanga