简体   繁体   中英

How Do I Access One Variable From Another Class?

I am not by my programming computer right now, so I can't post the code. I've been taking online lessons that I bought from Udemy so I'm still learning a lot.

I've looked at a decent number of posts, but the code they posts seem so long and complicated that it gets confusing. I have tried using a static variable, but the data needs to be changeable .

This is in android studios. How do I access the data from one class in another class?

Class One: //Class name is "ClassOne"

//Integer is an int named myNum and is equal to 1 .

Class Two: //Class name is "ClassTwo"

//I want my new int, myNewInt , to be equal to myNum .

There are couple of ways to do it.

  1. Create an object of Class One and access fields via that object or create getter and setter methods.
  2. Declare the field as static and access directly.
  • If the field myNum is declared as public , you can access it by any other class by typing the name of the object instance.myNu

  • If the filed myNum is declared as public static , you can access it from any other class by typing the name of the class.myNum

  • If the field myNum is private, you need getters and setters, namely, methods to access the file from an instance of the class that contains it. Google them to get up to speed on why they're useful and why you should use them.

Ex.

//public

ClassOne instance = new ClassOne();

ClassTwo instante2 = new ClassTwo();

instance2.myNewInt = instance.myNum;

//public static

ClassTwo instante2 = new ClassTwo();

instance2.myNewInt = ClassOne.myNum;

//getter

 ClassOne instance = new ClassOne();

 ClassTwo instante2 = new ClassTwo();

 instance2.myNewInt = instance.getMyNum();

 //and inside of ClassOne you'll have

  private int MyNum = 5;

  public getMyNum(){

     return MyNum;  

  }

Note:

If the variable was only declared locally (inside the body of one of ClassOne's methods), you're gonna need to assign it to a filed, so that you can later access it from other classes.

Reading Material:

Getters and Setters

Access modifiers

You should create a getter method in the first class

public int getMyNum(){
         return myNum;
}

In the second class you should have a setter method for the field myNewInt

public void setMyNewInt(int num){ this.myNewInt = num; }

And wherever you are running the code

myObject2.setMyNewInt(myObject1.getMyNum());

Sorry if there's any mistake, wrote this on the phone in a bus xD

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