Search code examples
javaabstract-classabstract-methods

Abstract Class Initialization


I have an abstract class:

abstract class Shape {

    public String color;
    public Shape() {
    }
     public void setColor(String c) {
        color = c;
    }
    public String getColor() {
        return color;
    }

    public double area() {
        return 0;
    }
}

Which provides non abstract methods and then i want to initialize it like:

     Shape object = new Shape();

so on initialization, it's still giving me an error, but why? If I provide one abstract method in the class, then it could be understandable that the class cannot be initialized. In this situation, why is it still giving an error? Any help would be appreciated


Solution

  • initialization its still giving me an error but why

    Because the class is abstract. An abstract class simply can't be instantiated directly, whether or not it's got abstract methods. From the JLS section 8.1.1.1:

    It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation expression (§15.9).

    If you haven't got any abstract methods and you want to be able to instantiate the class directly, make the class non-abstract. The only reason to make a class with no abstract methods abstract is to force the use of concrete subclasses.