abstract static classes in java giving error illegal combination of modifiers
Asked Answered
S

3

6
abstract class AbstractCase2 {
    abstract static void simpleMethod1();//giving error
}

class Case2 extends AbstractCase2 {
    static void simpleMethod1() {
    System.out.println("Within simpleMethod1");
}
    public static void main(String args[]) {            
    simpleMethod1();            
    System.out.println("with AwM");
    }     
}

Getting error:

C:\>javac Case2.java
Case2.java:8: error: illegal combination of modifiers: abstract and static
        abstract static void simpleMethod1();
                      ^
1 error
Sporophyll answered 14/4, 2013 at 4:38 Comment(0)
O
14

How can static method be abstract? static methods are not overridden!!

If you want to make your method abstract, make it non static

Abstract methods are designing constructs. You create abstract methods because you want your child classes to override them but static methods are associated with classes not their instance so they can't be overridden.

Orlando answered 14/4, 2013 at 4:39 Comment(3)
Why can't I tell the compiler that one of the child classes will implement the static method? This just seems ridiculous.Dael
@BrianHannay: When static methods cannot be overridden then child classes don't come into picture.Orlando
I feel like I am getting into this debate...Dael
H
9

static abstract makes your compiler bang its head.

You're pulling it from different directions.

static: Hey compiler, here's the code of my method, ready to be used whenever you need it, even if you don't create an instance.

abstract: Hey compiler, I'll put code in my method in the future, on one of the sub-classes.

Compiler: So do you have code or what? Oh no! Let me throw an error...

Hydroscope answered 14/4, 2013 at 5:16 Comment(1)
@OdedBreiner a close relative of polymorphismDael
R
2

Abstract and static are an illegal combination because abstract methods don't have a body, and static methods can be called without an object of the abstract class. When we don't have a body for a function, how can we call the function? We cannot call a function with just a prototype without defining it.

Abstract functions can be non-static. This is because non-static functions need an object to be called and objects for a class which inherits from an abstract class can only be created if and only if it overrides all the abstract functions of its parents. So, we cannot create an object without giving a body to the parents abstract functions and thus resolving the ambiguity.

Rabah answered 28/6, 2018 at 1:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.