简体   繁体   中英

Accesing a method from another class file?

I need to acces a variable (an int) from another class file. How would I do this? It's a public int, I need to get the int value and put it into a file.

If you have an instance:

AnotherClass another = new AnotherClass();

Then if the field (instance variable) is public:

another.someField;

or if you have a getter method

another.getSomeField(); 

If none of these is true - add a getter method (this is the preferred way to access instance variables).

If you can't change the class - as a last resort you can use reflection .

Example:


    MyClass myclass = new MyClass();
    System.out.print(myclass.myint)

Best practice code states that if the variable is not a Static Final, then you should create getters & setters inside the class:

public class Main{
   int variableName;

   public int getVariableName(){
       return this.variableName;
   }
   public setVariableName(int variableName){
       this.variableName = variableName;
   }
}

If you want to acess it from another class file then you have to instantiate an Object and then access it using the public method:

Main m = new Main();
int a = m.getVariableName();

Hope it helps.

If you have an instance of that other class, you access it as {instance}.varable.

That varaiable need to either be public, or it needs to be in the same package and not private, or it must be a protected variable in a superclass.

If the variable is static, then you don't need an instance of that class, you would access it like {ClassName}.variable.

Far and away the best thing to do here would be to make the int you need to access a Property of the other class and then access it with a 'getter' method.

Basically, in the other class, do this:

public int Number    
{
  get
  {
    return number;
  }
  set
  {
    number = value;
  }
}
private int number;

Doing this allows you to easily set that in to something else if you need to or to get it's current value. To do this, create an instance of the "AnotherClass" as Bozho already explained.

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