How to Use Java Encapsulation in Java


In this example we will show you how to use java encapsulation (getters and setters) in Java.

Source Code

package com.beginner.examples;

class Girl {
  private String name;
  
  // java encapsulation (getters and setters)
  public String getName() {
      return name;
  }

  public void setName(String name) {
        this.name = name;
  }
}

public class Encapsulation {
  public static void main(String[] args) {
    Girl g = new Girl();
    g.setName("Lucky");
    System.out.println(g.getName());
  }
}

Output:

Lucky
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments