static method declaration in abstract class

102 views Asked by At

I am trying to write a static method inside an abstract class, and as per my understanding, it is legal to create static methods under abstract class. However, the factory class I am trying to create keeps giving me the error: Illegal static declaration in inner class.

public abstract class Employee{
    protected String name;
    protected int hours;

    public String getName(){
        return name;
    }
    public int getHours(){
        return hours;
    }

    public abstract String getType();

    public Employee(String name, int hours){
        this.name=name;
        this.hours=hours;
    }

    public abstract double totalPay();


    public static Employee factory(String name, String type, int hours, double wage, double salary){
        if(type.equals("SALARIED")||type.equals("Salaried")||type.equals("salaried")){
            Employee object=new SalariedEmployee(salary, name, hours);
            return object;
        }
        else if(type.equals("HOURLY")||type.equals("Hourly")||type.equals("hourly")){
            Employee object=new HourlyEmployee(wage);
            return object;
        }
        else{
            return null;
        }
    }
}
2

There are 2 answers

0
Anand S Kumar On

Filename of the class was not Employee.java , for public classes, the file which houses the class needs to be named - .java . In OP example - Employee.java .

Though the error that comes when a public class is defined in a file with a different name is -

class Employee is public, should be declared in a file named Employee.java
1
Gourav Roy On

Inner class cannot have a static member

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

For reference: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html