Open In App

Why can’t static methods be abstract in Java?

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




// Java program to demonstrate
// abstract static method
 
import java.io.*;
 
// super-class A
abstract class A {
 
    // abstract static method func
    // it has no body
    abstract static void func();
}
 
// subclass class B
class B extends A {
 
    // class B must override func() method
    static void func()
    {
        System.out.println(
            "Static abstract"
            + " method implemented.");
    }
}
 
// Driver class
public class Demo {
    public static void main(String args[])
    {
 
        // Calling the abstract
        // static method func()
        B.func();
    }
}

The above code is incorrect as static methods cannot be abstract. When run, the Compilation Error that occurs is:
Compilation Error: 
 



prog.java:12: error: illegal combination of modifiers: abstract and static
    abstract static void func();
                         ^
1 error

What will happen if a static method is made abstract?
Assuming we make a static method abstract. Then that method will be written as: 
 

public abstract static void func();

 



Now considering Scenario 1, if the func method is described as abstract, it must have a definition in the subclass. But according to Scenario 2, the static func method cannot be overridden in any subclass and hence it cannot have a definition then. So the scenarios seem to contradict each other. Hence our assumption for static func method to be abstract fails. Therefore, a static method cannot be abstract.
Then that method will be coded as: 
 

public static void func();

Example: 
 




// Java program to demonstrate
// abstract static method
 
import java.io.*;
 
// super-class A
abstract class A {
 
    // static method func
    static void func()
    {
        System.out.println(
            "Static method implemented.");
    }
 
    // abstract method func1
    // it has no body
    abstract void func1();
}
 
// subclass class B
class B extends A {
 
    // class B must override func1() method
    void func1()
    {
        System.out.println(
            "Abstract method implemented.");
    }
}
 
// Driver class
public class Demo {
    public static void main(String args[])
    {
 
        // Calling the abstract
        // static method func()
        B.func();
        B b = new B();
        b.func1();
    }
}

Output: 
Static method implemented.
Abstract method implemented.

 


Article Tags :