i have a Emp class which have one property empName.i am setting this property in empCreate class.i want to get this property in Main class.
public class Main {
public static void main(String[] args) {
// here i want to get empName which i set it in empCreate.java
}
}
how i can do this. please suggest.
i have Emp.java:
public class Emp {
private String empName;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
and empCreate.java:
public class empCreate {
public static void main(String args[]) {
Emp emp= new Emp();
emp.setEmpName("abc");
}
}
i want to get this property in Main.java which i set it in empCreate.java
You can't have two main methods. Anyway, I strongly suggest you read the Declaring Member Variables tutorial. This is very basic stuff.
I recommend you refactor your empCreate
class to include a constructor and a getter for your Emp
instance. For instance,
public class empCreate {
private Emp emp;
public empCreate() {
emp = new Emp();
emp.setEmpName("abc");
}
public Emp getEmp(){
return emp;
}
}
And then, in your Main
class, you can simply do the following -
public class Main {
public static void main(String[] args) {
empCreate ec = new empCreate();
String empName = ec.getEmp().getEmpName(); // obtain the emp name
}
}
Add a method to Emp
called getName()
that returns the name. Then invoke that method when you want the name.
class Emp
{
String name;
....
public String getName() { return this.name; }
....
}
You can call it by creating a new instance of empCreate or directly calling that property after giving an static reference to empCreate.
精彩评论