How to use the variable of one class into another class using Java
The most appropriate way is to use the get() function to access the data, and the set() function to modify the data. This is encapsulation, and the purpose is to be able to change the logic of a class without having to modify the classes where you use it. For example:
- class Person {
- // usually this value is not assigned in this way, it is just an example
- private String fullname = "John Doe";
- public String getFullname() {
- return this.fullname;
- }
- }
- class ShowPersonInfo {
- public static void main(String [] args) {
- Person p = new Person();
- System.out.println("Person full name is:" + p.getFullname());
- }
- }
Now if you need to change your person class:
- class Person {
- private String name = "John";
- private String lastname = "Doe";
- ...
- }
You just have to modify the getFullname() method of that class, and you would leave the ShowPersonInfo class intact:
- class Person {
- ...
- public String getFullname() {
- return this.name + " " + this.lastname;
- }
- }