Reputation: 35
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
Reputation: 15212
You can't instantiate an abstract
class. You have three options :
EmployeeFileProcessor
to be a non-abstract class by removing abstract
from the class declaration.EmployeeFileProcessor process = new EmployeeFileProcessor() { };
(Not recommended)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
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
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