- How do I access variables from another class in Java?
- 2 Answers 2
- Access a Variable From Another Class in Java
- Access Static Variables in Java
- Access Instance Variables in Java
- Access Variables in a Subclass in Java
- Related Article — Java Variable
- Related Article — Java Class
- How to Access Variable From Another Class in Java?
- Method 1: Create Object of Another Class in Main Class
- Method 2: Extend Another Class in Main Class
How do I access variables from another class in Java?
I have a class called Customer with customerName, customerEmail and customerAddress as variables set in an object called a. How do I print the variables customerName, customerEmail and customerAddress in another class called BookingConfirmation? I tried:
System.out.println("Thanks for your booking " + a.getCustomerName());
public class Customer < String customerName; String customerEmail; String customerAddress; public static void customerDetails() throws IOException < Customer a = new Customer(); Scanner seekName = new Scanner(System.in); // Create a Scanner object System.out.print("Your name: "); a.customerName = seekName.nextLine(); // Read user input Scanner seekEmail = new Scanner(System.in); // Create a Scanner object System.out.print("Your email: "); a.customerEmail = seekEmail.nextLine(); // Read user input Scanner seekAddress = new Scanner(System.in); // Create a Scanner object System.out.print("Your residential address: "); a.customerAddress = seekAddress.nextLine(); // Read user input System.out.println("Thanks for your booking " + a.getCustomerName()); System.out.println("Eemail: " + a.getCustomerEmail()); System.out.println("Address: " + a.getCustomerAddress()); System.out.println(); >public String getCustomerName() < return customerName; >public String getCustomerEmail() < return customerEmail; >public String getCustomerAddress() < return customerAddress; >>
Theoretically you can’t access a local variable(in this case a ) from outside its scope. In your example the object a has method scope and won’t be accessible from outside customerDetails() function.
You should return that Customer object you made in your static method, and then you have a valid factory pattern. Also, encapsulate your fields (make them private , look up getters and setters)
What you can do is change the return type of customerDetails() to Customer instead of void , and return the object a . And try accessing it from within your BookingConfirmation class.
2 Answers 2
I’m not sure I know what you’re asking, but it seems that you could do the following:
- Have the customerDetails() method return a (the created Customer object) as the result of the method.
- Call Customer.customerDetails() from BookingConfirmation , and save returned value in a local variable Customer a .
- Then you can call System.out.println(«Thanks for your booking » + a.getCustomerName()); inside the BookingConfirmation code.
I just want to copy the 3 variables from Customer class and print them in sentences (using system.out.println() all done in terminal) in BookingConfirmation class. Scanner gets name in Customer class. BookingConformation class prints. «We have received your hotel booking (name from Customer class — variable customerName).
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"
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.
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.
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
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();
Access a Variable From Another Class in Java
- Access Static Variables in Java
- Access Instance Variables in Java
- Access Variables in a Subclass in Java
This tutorial introduces how to call a variable from another class in Java. We’ve included some example programs you can follow to execute this project.
Access Static Variables in Java
A variable defines as the name used for holding a value of any type during program execution. In Java, a variable can be static, local, or instance. If a variable is static, we can access it by using the class name. If a variable is an instance, we must use a class object to access the variable. Let’s understand further through the examples we have.
In the program below, we are accessing the static variable of the Test class in SimpleTesting by using the class name. See, we did not create the object of the class; this is how we can access static variables anywhere in the Java source code.
public class SimpleTesting public static void main(String[] args) Test t = new Test(); t.add(10, 20); int result = Test.sum; // accessing variable System.out.println("sum = "+result); > > class Test static int sum; void add(int a, int b) sum = a+b; > >
Access Instance Variables in Java
Here, we are accessing instance variables from another class. See, we used the object of the Test class to access its instance variable. You can only access instance variables by using the class object. Check the sample program below.
public class SimpleTesting public static void main(String[] args) Test t = new Test(); t.add(10, 20); int result = t.sum; // accessing variable System.out.println("sum = "+result); > > class Test int sum; void add(int a, int b) sum = a+b; > >
Access Variables in a Subclass in Java
Suppose a class inherits another class; the variables of the parent class become implicitly accessible inside the subclass. You can access all the variables by using the subclass object, and you don’t have to create an object of the parent class. This scenario only happens when the class is extended; otherwise, the only way to access it is by using the subclass.
public class SimpleTesting extends Test public static void main(String[] args) SimpleTesting st = new SimpleTesting(); st.add(10,20); System.out.println("sum = "+st.sum); > > class Test int sum; void add(int a, int b) sum = a+b; > >
Related Article — Java Variable
Related Article — Java Class
How to Access Variable From Another Class in Java?
In this article, we will learn how to access variable from another class in java.
- Create an object of another class in the main class
- Extend another class in the main class
Let us take a look at both these methods one by one with the help of sample programs.
Method 1: Create Object of Another Class in Main Class
In the following example, to access the variable ‘a’ of class A, we create its object in another class B. After that, we use this object to use the value of variable ‘a’ in class B. Note that if we do not initialize this variable, then its default value is taken to be zero.
Method 2: Extend Another Class in Main Class
If we wish to access a variable from another class, we have a keyword, ‘extends’, which we can use in the child class. Using it, the child class can inherit all the properties of the parent class.
In the above program, we created two classes, namely ‘A’ and ‘B’. In class ‘A’, we defined an instance variable ‘a’ with a value of 10. The other class ‘B’, extends the class ‘A’ using the ‘extends’ keyword. So, it can use the instance variable of class ‘A’ by creating its object. So, the child class inherits all the properties of its parent class.
If we wish to use an instance variable, then we have to use objects to call them. Every time you create a new object from a class, you get a new copy of each of the class’s instance variables. These copies are associated with the new object. So, each and every instance variable is accessed by the object.