Search code examples
javainheritanceabstractsuper

Problem with abstract methods using inheritance


I am learning inheritance in Java, and I am trying to solve the error in the following code:

public static void main(String[] args) {
    Yellow yellow=new Yellow("yellow");
    yellow.ChangeColor();
}
abstract class SpecialColor{
    String color;
    
    SpecialColor(String color){
        this.color=color;
    }

    abstract void ChangeColor();
    
    public String ShowColor(String color) {
        return color;
    }
    
}

class Yellow extends SpecialColor{

    Yellow(String color) {
        super(color);
        
    }
    
    @Override
    void ChangeColor() {
        color="yellow";
        System.out.println("The color is "+color);
    }
    
}

The task I am trying to do basically says that I need to create an abstract class SpecialColor with 2 properties - the color name (String) and two methods - abstract void ChangeColor(), the other displays the color name, while class Yellow extends this class and implements abstract methods and the name needs to change to "yellow", and to show the use of these classes in main. The error I have is in the 1st line of code in the main method - "No enclosing instance of type is accessible", which I tried to solve making the Yellow class static, but then a new error pops up on super(color) line that says "No enclosing instance of type sestijanuar8 is available due to some intermediate constructor invocation". I am having a hard time understanding abstract classes and methods, so any form of help would be appreciated!


Solution

  • Your classes are inside another class, and they are not static, so they are inner classes. That means they can only be instantiated with reference to an instance of the containing class.

    Either move them out of the containing class, or declare them static. Then you will be able to instantiate them.