USING GETTER AND SETTER IN JAVA
Getters and Setters are required to protect your data from interference from outside of the class. In my previous post, you can see the class and object were in public domain. So anyone can set the value from outside of the class by just using .. So to prevent anyone from using your variable you can use getter and setter.
This is how setter and getter works. I passed variable name with datatype string as parameter to setName method. this.name=name means that whatever you pass string value to the set method, the variable Name of GetSet class would have that value that you passed in the parameter. The same works with setAge method. getName would simply return that name value.
package Lesson1;
public class GetSet {
String Name;
int Age;
public static void main(String[] args) {
GetSet student= new GetSet();
student.setName("Danny");
student.setAge(20);
System.out.println(student.getName() + " is " + student.getAge() + " years old.");
}
public void setName(String Name) {
this.Name=Name;
}
public void setAge(int Age) {
this.Age=Age;
}
public String getName() {
return Name;
}
public Integer getAge() {
return Age;
}
}
The output of this code when executed is as below:
Please note this code is not confounding one. I am still learning the Java programming and whatever I code I wrote in those inline blocks, it's for layman only so that they can easily understood the logic. Eclipse IDE allows you to automatically generate getter and setter so you don't have to take any extra hard work to write the code manually.
Leave USING GETTER AND SETTER IN JAVA to:
Read more #java posts
Best Posts From Leo Umesh
We have not curated any of leoumesh's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From Leo Umesh
- The Tattoo of My Newborn Baby Girl Forever Inked on My Skin
- Long Weekend Food Feast With Wife
- String Manipulation in C#: Part 2
- String Manipulation in C#
- Introduction to C# and .NET
- Weekend Escape To Falls
- Evening Barbecue With Favourite Beer 🍺 🍻
- NumPy Broadcasting
- Summer BBQ
- Review of "The Day of The Jackal" Series
- Wonders of Wave Rock, Western Australia
- Trying To Make Authentic Chicken Dum Biryani At Home
- Beautiful Ocean Lookout in South West Australia
- Esperance: Hidden Paradise of Western Australia
- Cruising Through Blue Haven Beach
- My First Tattoo
- Exploring Flavoursome Veggie Indian Cuisines
- Australia's Popular Drink: Homemade
- An Everlasting Flowers
- Unexpected Rainbow At Wellington Dam, Western Australia