Coolunized5
Coolunized5

Reputation: 35

How to instantiate an abstract class in Java?

I have a public abstract class named EmployeeFileProcessor, which is also what I am trying to instantiate. How would I easily fix this code so that I can instantiate this?

public abstract class EmployeeFileProcessor
{
    public static void main(String[] args) throws Exception
    {   
        EmployeeFileProcessor process = new EmployeeFileProcessor();
        //Non important code here
        process.writeFullTimeEmployee(user_input1, FtCollection[0]);
        //Defined in another class (method writeFullTimeEmployee)
        process.readFulltimeEmployee(user_input1);
        //Defined in another class (method readFullTimeEmployee)
    }
}

How would I be able to use the 'process'?

Upvotes: 1

Views: 6668

Answers (3)

Chetan Kinger
Chetan Kinger

Reputation: 15212

You can't instantiate an abstract class. You have three options :

  1. Change EmployeeFileProcessor to be a non-abstract class by removing abstract from the class declaration.
  2. Instantiate an anonymous inner subclass of your class instead : EmployeeFileProcessor process = new EmployeeFileProcessor() { }; (Not recommended)
  3. Change all the methods and fields in EmployeeFileProcessor to static. This way, you no longer need to instantiate EmployeeFileProcessor. (Not recommended unless your class doesn't have state)

In other words, don't create an abstract class if you want to instantiate it.

Upvotes: 3

bhspencer
bhspencer

Reputation: 13560

You cannot directly create an instance of an abstract class. You must first define a class that extends the abstract class and then create an instance of that class.

e.g.

public ConcreteEmployeeFileProcessor extends EmployeeFileProcessor {

}

You can then create instances of ConcreteEmployeeFileProcessor but reference it using the abstract type.

EmployeeFileProcessor instance = new ConcreteEmployeeFileProcessor();

Upvotes: 3

pnadczuk
pnadczuk

Reputation: 927

Abstract class is a class that you cannot instantiate by definition. It is similar to the interface, except for the ability to declare fields and actually implement functions in case they are not overriden (for Java 8 you can use default methods in the interfaces).

Anyway, if you really want to instantiate this class in a default way, you could try to do it like this:

EmployeeFileProcessor process = new EmployeeFileProcessor() {};

But it's most likely a very poor design ;-)

Upvotes: 2

Related Questions