开发者

get the object property in another class [closed]

It's difficult to 开发者_如何学JAVAtell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜