Casa > H > How To Use The Variable Of One Class Into Another Class Using Java

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:

  1. class Person { 
  2. // usually this value is not assigned in this way, it is just an example 
  3. private String fullname = "John Doe"; 
  4. public String getFullname() { 
  5. return this.fullname; 
  6. class ShowPersonInfo { 
  7. public static void main(String [] args) { 
  8. Person p = new Person(); 
  9. System.out.println("Person full name is:" + p.getFullname()); 

Now if you need to change your person class:

  1. class Person { 
  2. private String name = "John"; 
  3. private String lastname = "Doe"; 
  4. ... 

You just have to modify the getFullname() method of that class, and you would leave the ShowPersonInfo class intact:

  1. class Person { 
  2. ... 
  3. public String getFullname() { 
  4. return this.name + " " + this.lastname; 

De Orman Orlando

Como escrever uma descrição de direitos autorais em nossos vídeos do YouTube :: A Disney é um monopólio?