Home > Net >  Java error: "Cannot instantiate the type..." and type mismatch
Java error: "Cannot instantiate the type..." and type mismatch

Time:12-17

How can I get rid of the error "Cannot instantiate the type..."?

I have an abstract class named Expression:

public abstract class Expression {
    private String expr;
        
    Expression(){}
    
    Expression(String expr){
        this.expr = expr;
    }
    
    public String getExpr() {
        return this.expr;
    }
}

And I have a class that inherits Expression:

public class Elements extends Expression {
    private List<String> elements = new ArrayList<>();
    
    Elements(List<String> elements){
        this.elements = elements;
    }
    
    public List<String> getElements(){
        return this.elements;
    }
}

And I also have a class that extends a generic class with parameter type Expression, and a method of return type Expression (this generic class is just a class generated by a parser generator):

public class AntlrToExpression extends ExprBaseVisitor<Expression> {
@Override
public Expression visitElements(ElementsContext ctx) {
        ElementContext element;
        List<String> elemList = new ArrayList<>();
        
        ElementsContext elements = ctx.elements();
        while(elements.getChildCount() > 1) {
            element = elements.element();
            elemList.add(element.getText());
            elements = elements.elements();
        }
        element = elements.element();
        elemList.add(element.getText());
        
        return new Elements(elemList); // Here I get errors saying "Cannot instantiate the type Elements" and "Type mismatch: cannot convert from Elements to Expression"
    }
}

All the classes above are defined in the same package. Hope my question is clear enough.

CodePudding user response:

Credit Makoto

You can't instantiate an abstract class.

You've got two options:

  • Remove abstract from the class declaration, or
  • Create another class to extend Expression, which can be instantiated.

CodePudding user response:

Maybe somewhere in your code, you try to instantiate Expression object. Since the Expression class is abstract, it cannot be instantiated. But these types of errors are caught by the IDE and at compilation.

It would help if you include the stack trace of the exception.

CodePudding user response:

You are returning Expression in the visitElements but try to return a new Element()

  • Related