Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java
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:
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 21-Jan-13 8:28am
Edited 21-Jan-13 8:30am
v2
Comments
Sergey Alexandrovich Kryukov at 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 at 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 at 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 at 21-Jan-13 16:01pm
   
in the uml diagram provided the instance variables are declared as private

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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
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.
  Permalink  
Comments
diego14567 at 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)



Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 21 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid