Hi, I have a java program with quite a lot of classes. I'm facing a problem with accessing some variables from another class. May I know how to I access it? Is it possible?

Recommended Answers

All 3 Replies

Declare that variable public, or better have public get methods:

class ClassA {
  private int value = 0;

  public int getValue() {
     return value;
  }
}
class ClassB {
  
   public static void main(String [] args) {
      ClassA cla = new ClassA();
      System.out.println(cla.getValue());
   }
}

Why do you want to get at the other class's data? Better to let that class tend to its own knitting.
The less data you share, the easier your code is to manage. Why is that? Well, if you have a class that depends on data from another class, sooner or later that other class is going to change in some way. Now you have to find everything that's depending on it being like it was, and fix it to do things the new way.
If the class works on its own data, you know by simple inspection what methods will need to change, because they're all in the class that you're already working on.

In the real world, there will be times when you will have getters, but every time you see a getter, you should be wondering how you could do away with it. Usually the answer will be to send instructions, not information.

Of course it's much better to have getters and setters than to leave classes public, or even protected, because then you at least have some control over what's getting set, but you should only have a getter or a setter when you absolutely know you need it.

The methods of an inner/nested class may also directly access the variables of its top-level class. So in some case one may declare a class entirely within the body of another class

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.