Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading