How Do I Access One Variable From Another Class?
If the field
myNum
is declared aspublic
, you can access it by
any other class by typing the name of the object instance.myNuIf the filed myNum is declared as
public static
, you can access it
from any other class by typing thename 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
How do I access variables from another class in Java?
If you simply want to access the value of a property from outside of the class, then you need to create getters for each one of the properties you want to retrieve.
If you want to modify these values from outside of the class, you need to create a setter.
Getters and Setters are simply methods that allow you to access properties of a class outside of it.
If you have the class Customer
and want to access and change it's name from outside, you'd create 2 methods,
//declare the property
private String name;
//getter
public String getName(){
return this.name;
}
//setter
public void setName(String newName){
this.name = newName;
}
//You can then instantiate a Customer object anywhere else and have access to those //properties
Customer cust = new Customer();
cust.setName("Mark")
System.out.println("Oh hi " + cust.getName());
//output "Oh hi Mark"
Read more on getters and setters
Also, best practices tip: instance variables should always be declared as private
to help encapsulation. If no access modifier is provided for an instance variable in Java, it defaults to the default
modifier, which makes the variable accessible for every class within the same package.
Edit:
Your specific error is that you are creating a new Customer
object within your customerDetails
method, and you're not returning this Customer
object. Therefore, as soon as the method has been executed, the Customer
object you created inside is destroyed (cleared from memory,Garbage collected), because there is no further reference to it.
You either need to
Method 1: Change the return type of your customerDetails method from void
to Customer
and add a return a
statement at the end, then you would simply need to instantiate a Customer object from your booking class, like so
public Customer customerDetails(){
Customer a = new Customer();
//your logic to set all of the properties
return a;
}
in your booking class
Customer myCust = new Customer();
myCust = myCust.customerDetails();
I would not prefer this method, because as you see, you're just creating an empty object then reassigning to it. You may alternatively add the static
keyword after public
so that you can call it without having instantiated an object of the class, like so
booking class
Customer myCust = Customer.customerDetails();
Method 2: remove the Customer a = new Customer()
from the customerDetails altogether and simply use this.name = sc.nextLine()
to set the name of whatever instance is calling this method.
Then on bookings class, instantiate a new Customer object and call the method.
Customer myCust = new Customer();
myCust.customerDetails();
how to use variable which is declare in another class
Options:
1.Use static variable:
Declare static String collect;
and access it from other class as <YourClassNmae>.collect;
where YourClassName is the class in which you have declared the static variable.
2.Use Application class
Create application class extending Application
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
Declare the application class name in manifest like:
<application
android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name">
Then in your activities you can get and set the variable like so:
// set
((MyApplication) this.getApplication()).setSomeVariable(collect);
// get
String collect = ((MyApplication) this.getApplication()).getSomeVariable();
Related Topics
Prevent Multiple Login Using the Same User Name and Password
How to Display Auto-Configuration Report When Running a Spring Boot Application
Java.Lang.Noclassdeffounderror: Org/Springframework/Core/Env/Configurableenvironment
How to Sort Integer Digits in Ascending Order Without Strings or Arrays
Update Objects in One List Based on Values from Second One Using Streams
The Group Coordinator Is Not Available-Kafka
Calculate the Number of Items Displayed by Recyclerview and Place in a Textview
Java 8 Streams: Multiple Filters Vs. Complex Condition
Generate Bank Account Number With Random
Java Classes to Generate the Given Json String
Regular Expression for Uppercase Letters in a String
How to Convert a One-Dimensional Array to Two-Dimensional Array in Java
Showing Morning, Afternoon, Evening, Night Message Based on Time in Java