简体   繁体   中英

Accessing a class' member variable from another class

Consider this example:

public class FirstClass {
    public static int x;

   public static void main(String[] args){
     x = 5;
     SecondClass sc = new SecondClass();
   }

   public int getX(){
     return x;
   }

}
//assume class SecondClass is in another File
public class SecondClass{}

I want to access variable x from class SecondClass and as far as I know there are two ways I can do this.

  1. In SecondClass class I can simply do FirstClass.x ---> do stuff. IntelliJ allows me to do this since x has public visibility.

  2. I make the constructor of SecondClass take a FirstClass fc as a parameter and then do this.fc = fc; while having declared it as a member variable after class declaration. Then, in the main I change the instance of SecondClass to SecondClass sc = new SecondClass(this); And now I can have access in SecondClass through fc.getX();

What is the difference between the two as I have never seen an explanation in this scenario ?

Apologies if my example is not abstract enough but I tried to make it as much as possible.

Thanks in advance.

  1. You can access variable x from Second Class by FirstClass.x because I think you have declared x as static. Otherwise, you cannot access like that. Then you have to create an object of First Class then you have to access that variable x .

  2. Don't pass the class in the constructor of Second Class. Just pass the variable x . This will be better. If we pass the class then we can do so many things from Second Class. For that reason, we will provide those data which are needed in Second Class.

    SecondClass sc = new SecondClass(x);

public class FirstClass {
    int x;
    ...... 
    public int getX(){
        return x;
    }
}

There is no maggic. it's by java specification. Controlling Access to Members of a Class

The four access levels are −

  • Visible to the package, the default. No modifiers are needed.
  • Visible to the class only (private)
  • Visible to the world (public)
  • Visible to the package and all subclasses (protected)

your case int x; has default access. All classes in some package have access to it.

public int getX()

you can get x variable everywhere by in your project.

FirstClass fc = new FirstClass(); int value = fc.getX();

You should use exactly this (call method instead of direct x) approach in 90% cases outside of your class and 10% getX() - inside class. There might be cases with testing , some extra logic for getX() -- but it's in common practice , not in your case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM