newbie Java question - non-static method cannot be referenced from a static context

G

G. Burton

This is probably painfully obvious to a real programmer... Attempts at
compiling the following program result in the message:
Employee.java:9: non-static method
initEmployee(java.lang.String,float,boolean)
cannot be referenced from a static context
initEmployee(FRED, 6012f, true);
^
1 error

This is the entire source java file:
public class Employee
{

public static void main(String[] args)
{
// final indicates a constant.
final String FRED = "Fred";
Employee emp = new Employee();
initEmployee(FRED, 6012f, true);
String currentName = emp.displayEmpName();
System.out.println(currentName);
}

public void initEmployee(String employeeName_In, float sal_In,
boolean activeInd_In)
{ name = employeeName_In;
salary = sal_In;
active_Ind = activeInd_In;
System.out.println("Name: "+name);
System.out.println("Salary: "+salary);
System.out.println("Active Indicator: "+active_Ind);
System.out.println("Init Done");
}

public String displayEmpName()
{ return name; }

private String name;
private float salary;
private boolean active_Ind;
}

Any help to get a beginner going would be greatly appreciated.

Thanks in advance!
 
B

Barry White

Hi,

initEmployee is an instance method (it acts on a specific instance of
the class) but you are calling it from a static context (the static main
method). If you just call initEmployee which instance are you referring
to (none). You need to call emp.initEmployee(...).

It's perfectly fine having the main method in a calss such as Employee
but I think if you are learning java it confuses things. Perhaps
something like:

public class TestEmployee
{
public static void main(String[] args)
{
Employee emp = new Employee();
emp.initEmployee("Fred", 6012f, true);
}
}

public class Emplyee
{ // etc

Regards,
Barry
 
S

Sudsy

G. Burton wrote:
public static void main(String[] args)
{
// final indicates a constant.
final String FRED = "Fred";
Employee emp = new Employee();
initEmployee(FRED, 6012f, true);

emp.initEmployee(FRED, 6012f, true);
String currentName = emp.displayEmpName();
System.out.println(currentName);
}
Any help to get a beginner going would be greatly appreciated.

Thanks in advance!

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,979
Messages
2,570,184
Members
46,721
Latest member
DollieSawt

Latest Threads

Top