Click here to Skip to main content
11,648,094 members (73,623 online)
Rate this: bad
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;
    // of code

Posted 21-Jan-13 8:28am
Edited 21-Jan-13 8:30am
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.
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.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
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)
class One
Two objTwo=new Two();
public void oneMethod()

Please write your question appropriately to get appropriate answer. Hope this example helps you understand your problem.
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)

  Print Answers RSS
0 F-ES Sitecore 395
1 330
2 DamithSL 300
3 OriginalGriff 277
4 CPallini 250
0 OriginalGriff 1,342
1 994
2 DamithSL 981
3 Sergey Alexandrovich Kryukov 893
4 CPallini 845

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

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100