Java Setters and Getters

 In object-oriented programming, setters and getters are methods used to set and retrieve the values of the private fields (attributes) of a class, respectively. They provide a way to encapsulate the internal state of an object, enabling controlled access to its data.

Here's a simple Java class with private fields, setters, and getters:

public class Person { private String name; private int age; // Setter for name public void setName(String name) { this.name = name; } // Getter for name public String getName() { return name; } // Setter for age public void setAge(int age) { this.age = age; } // Getter for age public int getAge() { return age; } }

Explanation:

  1. private String name; and private int age;: These are private fields of the Person class. They cannot be accessed directly from outside the class.

  2. public void setName(String name): This is the setter method for the name field. It allows setting the value of the name field from outside the class.

  3. public String getName(): This is the getter method for the name field. It returns the value of the name field.

  4. public void setAge(int age): This is the setter method for the age field.

  5. public int getAge(): This is the getter method for the age field.

Now, let's see how you can use these setters and getters:

public class Main { public static void main(String[] args) { Person person = new Person(); // Using setters to set values person.setName("Alice"); person.setAge(30); // Using getters to retrieve values System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); } }

In this example:

  • We create a new Person object.
  • We use the setter methods setName() and setAge() to set the name and age fields of the person object.
  • We use the getter methods getName() and getAge() to retrieve the values of the name and age fields and print them.


Previous Post Next Post

Welcome, New Friend!

We're excited to have you here for the first time!

Enjoy your colorful journey with us!

Welcome Back!

Great to see you Again

If you like the content share to help someone

Thanks

Contact Form