+ 1

Hi guys. Could u anyone explaine me about getter and setter?

Getter and Setter

27th Nov 2016, 1:25 PM
Vinoth Balendran
Vinoth Balendran - avatar
2 Respostas
+ 3
Getter and Setter are two different methods that are used in OOP to Encapsulate dhe data. What does it mean Data Encapsulation ? Data Encapsulation means not allowing to get access in variables of your class directly or changing them. So what we do ? we create two methods for an attribute one to get the value of that specific attribute the other to change that value or we can leave it readonly I will demonstrate it in a single example below: public class Hello{ \\we have two attributes private String name; private String lastName; \\we are creating two constructors one will be blank and the other one will help us to intiliaze our variables (give them data); public Hello(){} \\we have a constructor if we want to initialize our variables or attributes public Hello(String name,String lastName){ this.name = name; this.lastName = lastName; } \\we dont want to acces directly to our methods and thats why we declared \\them private \\Let's use getter methods to get data public String getName(){ return name; } public String getLastName(){ return lastName; } \\We want to change the values of our variables public void setName(String name){ this.name = name; } public void setLastName(String lastName){ this.lastName = lastName; } \\ Let's Create a String Format For Name and Last Name public String toString(){ return " This is my String Format : "+name+" "+lastName ; } \\now lets create the main Class public static void main(String [] args){ \\Now we will create a object of class Hello and we will use two setter methods \\to initialize two variables and then print those variables data Hello hello1 = new Hello(); hello1.setName("Brat"); hello1.setLastName("Pitt"); System.out.println(hello1); \\Now we gonna create another object and we will initialize data with \\constructor Hello hello2 = new Hello("Angelina","Jolie"); System.out.println(hello2.getName()); System.out.println(hello2.getLastName()); } }
27th Nov 2016, 3:28 PM
( ͡° ͜ʖ ͡°)
+ 1
Sorry if any brackets is missing I wrote the code in the comment here not in any editor or IDE
27th Nov 2016, 3:29 PM
( ͡° ͜ʖ ͡°)