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;
- }
- }
Articoli simili
- In One Punch Man, chi sono i rank 1 di ogni classe (Rank 1 di S-Class, Rank 1 di A-Class, Rank 1 di B-Class, Rank 1 di C-Class e Rank 1 di D-Class)?
- How to put a variable into an array in Python
- How to convert hex into a string using Python
- How to make a to-do-list using PHP and connecting it using MySQL