Click here to Skip to main content
11,920,394 members (58,656 online)
Rate this:
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 9:28am
Edited 21-Jan-13 9:30am
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.
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.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

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 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 OriginalGriff 415
1 phil.o 170
2 Dave Kreskowiak 155
3 KrunalRohit 134
4 F-ES Sitecore 130
0 OriginalGriff 6,778
1 KrunalRohit 4,530
2 Sergey Alexandrovich Kryukov 3,203
3 George Jonsson 2,815
4 Suvendu Shekhar Giri 2,181

Advertise | Privacy | Mobile
Web03 | 2.8.151120.1 | 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