Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have looked through many sources, but I am unable to come up with a solution as to how I would retrieve another classes instance variable to put in a method of another class for example:
Java
public class Example{
    private ExampleTwo info;

    public void setInfo(int one, int two){   // i am trying to set the parameters so it can access the instance variable from ExampleTwo class

    }

}

public class ExampleTwo{
    private int one;
    private int two;

    //....rest of code

}
Posted
Updated 21-Jan-13 8:30am
v2
Comments
Sergey Alexandrovich Kryukov 21-Jan-13 14:38pm    
What could be a problem? sounds absolutely trivial... Of course, if you are not even trying to access the instance of one class in another, you get nothing. Your code sample looks totally irrelevant to the question. The answer would be: just do it.
—SA
diego14567 21-Jan-13 14:47pm    
im having trouble acessing the instance of exampleTwo as i keep getting an error when i try to call this.one=one;,this.two=two; or when i try to extend exampleTwo and calling the super
Jibesh 21-Jan-13 15:51pm    
the variable one and two are declared as private so it never able to access outside the class. change it to public to access.
diego14567 21-Jan-13 16:01pm    
in the uml diagram provided the instance variables are declared as private

1 solution

Remember, java does not have Property like C#. So you need to play a little tricky here. Adopt the property style.

When you want to access a class variable which is private, write two public methods. see the following example
Java
class Two
{
private int var;

public int getVar()
{
return var;
}

public void setVar(int var)
{
this.var=var;
}
}

class One
{
Two objTwo=new Two();
public void oneMethod()
{
objTwo.setVar(30);
System.out.println(objTwo.getVar());

}
}


Please write your question appropriately to get appropriate answer. Hope this example helps you understand your problem.
 
Share this answer
 
Comments
diego14567 21-Jan-13 18:23pm    
thanks for some reason i was trying to omit the object and was just calling the other classes method

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900