Best way to access variables from another class?
In general there are 2 ways to access a variable from another class:
- You create an object of that class. Then this object has all the variables from the scope of that class assigned to it. For example:
Test t = new Test();
t.name = "test";
- You can also create a static variable. Then the variable is assigned to the class not the object of that class. This way you will not need to create an object, but all instances of the class will share the same variable.
//In the scope of the class
static String name;
-------------------------
//when classing the class
Test.name = "The Name of the Test";
If you do not want to create a new instance of a class every time, and always use the same instance, you can create a singleton object. You write a getter method that gets you the object. It looks like this:
public class Test {
Test t;
public static void main(String[] args) {
t = new Test();
}
public Test getTest() {
if (t != null) {
return t;
} else {
t = new Test();
return t;
}
}
}
I see you work with a JFrame. Then you will probably want to make it a singleton. Else you will open a new instance of the JFrame every time you call upon it, which is not recommended.
Does this answer your question?
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 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
Accessing a class' member variable from another class
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
Can't access a variable from another class in Java?
You need to say Person.numFriends
. This is because numFriends is a static member of the Person class, so you need to use the Person class to reference numFriends.
Related Topics
How to Convert a Byte Array to Base64 in Java
Why Equals() Method When We Have == Operator
Why Doesn't Java Map Extend Collection
Java Annotations Values Provided in Dynamic Manner
How to Turn a String into a Inputstreamreader in Java
How to Calculate the Number of Rows (And Columns in Each Row) a Text Takes in a Jtextarea
Use Cases and Examples of Gof Decorator Pattern for Io
Maven - Always Download Sources and Javadocs
Green Threads VS Non Green Threads
What Is a Difference Between <? Super E> and <? Extends E>
Jre 1.7 - Java Version - Returns: Java/Lang/Noclassdeffounderror: Java/Lang/Object
How Do Synchronized Static Methods Work in Java and How to Use It for Loading Hibernate Entities
Determine Which Jar File a Class Is From
When Should I Use the "Strictfp" Keyword in Java
&& (And) and || (Or) in If Statements
How to Watch for Single File Change with Watchservice (Not the Whole Directory)