Getter and Setter in Java - Java Getter and Setter with Example

 

Java Getter and Setter with Example

Getter and Setter in Java

Getter and Setter in java is very important for encapsulation (it is the wrapping of variables and methods into a single unit) data from the outside world. Getter and setter methods are basically used to get and maneuver private variables in a different class.  The getter method retrieves an element of the same name while a Setter sets the element.  Getter and Setter's method is also known as Accessor method.

public class SetterAndGetter 

{ 

    private String name;

    private String idCourse;

    private int age;

 

    public String getName() {

        return name;

    }

   public void setName(String name) 

   {

        this.name = name;

    }

  public String getIdCourse()

  {

        return idCourse;

   }

  public void setIdCourse(String idCourse)

 {

        this.idCourse = idCourse;

    }

 

    public int getAge() {

        return age;

    }

 

    public void setAge(int age) {

        this.age = age;

    }

}

Here private variables are name, idCourse, and age and it cannot be accessed directly from the outside world. In setXXX and getXXX methods facilitate to access the private variables.

Now from another class, those private variables can be accessed very easily

package encapsulation;

public class Encapsulation {

 

    public static void main(String[] args) {

        SetterAndGetter encap=new SetterAndGetter();

        encap.setAge(20);

        encap.setIdCourse("BCA");

        encap.setName("Kamal");

        System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge()+ "Course :"+encap.getIdCourse());

       

    }   

}

In the above example, setter and getter methods are protecting variable’s private String name,

private String idCourse, private int age value from unexpected changes by the outside world or class or from the caller code.

Setter and Getter in java a few important points

  • The hidden variable (private modifier) can be accessed only through a getter and setter that is encapsulated. Encapsulation is wrapping of data into a single unit.
  • The setter/getter methods/ function are used to allot or change and access values of the instance variables of a class.
  • Getters and setters are also known as accessors and mutators, respectively.
  • Encapsulation is associated with getting or setting method.
  • Hiding the internal variable’s property while revealing a property using an alternative representation.
  • Protect a public interface from change. It allows the public interface to remain constant while the execution changes without affecting existing values.

More tutorial and examples of java

Loops in Java - Java loop explained with examples



Java program for Pronic Number


SHARE THIS
Previous Post
Next Post