Getter and Setter in java

When we create a private variable in one class than we can not call that variable in another class so to access the variable in another class we use Getter and Setter.

The get method returns the variable value, and the set method sets the value.

Syntax of Getter and Setter in java.

class  student{
private byte id;
private String name;
public byte getId(){
return id;
}
public void setId(byte i){
id=i;
}
public String getName(){
return name;
}
public void setName(String n){
name=n;
}

}
And full program of the Getter and Setter.
 package com.ritesh;
class student{
private byte id;
private String name;
public byte getId(){
return id;
}
public void setId(byte i){
id=i;
}
public String getName(){
return name;
}
public void setName(String n){
name=n;
}

}

public class getter_setter {
public static void main(String[] args) {
student sc=new student();
sc.setId((byte) 33);
sc.setName("Ritesh Regmi");
System.out.println(sc.getId());
System.out.println(sc.getName());


}
}

Now we are seeing another program.
 package com.ritesh;
class line{
private int num;
private String name;

public int getNum(){
return num;
}
public void setNum(int n1){
num=n1;q
}
public void setName(String n2){
name=n2;

}
public String getName(){
return name;
}

}

public class get1 {
public static void main(String[] args) {
line sc=new line();
sc.setName("Ritesh Regmi");
sc.setNum(2);
System.out.println(sc.getNum());
System.out.println(sc.getName());

}
}

Comments