
How to pass variable from one class to another in java?

Example:
public class Class1 { //Class1
private String name = "Class1";
private int IdNo = 20;
public void class1Method() {
System.out.println("Welcome in " + name + " Its id number : " + IdNo);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIdNo() {
return IdNo;
}
public void setIdNo(int idNo) {
IdNo = idNo;
}
}
//Another class Class2.
public class Class2 {
public static void main(String[] args) {
Class1 class1 = new Class1(); // Creating object of Class1
String name = "Class2";
System.out.println("Welcome in " + name);
System.out.println("Another Class variables value:" + class1.getIdNo()
+ " and " + class1.getName());
class1.class1Method();
}
}
Description: In Class1, there is two private variables one is String type and another is int type. Since these variables are private so we can?t access these directly into another class. So we will create getter and setter method of these variables. In Class2 ,create object of Class1 as Class1 class1 = new Class1(); Now you can use its methods and variable through by calling Class1 getter methods. If there is public variable in Class1 then you can access them directly by Class1 object as class1.name.