Friday, May 29, 2015

Getters Setters

package package1;

// ENCAPSULATION
// GETTERS and SETTERS

public class Class1 {

// Encapsulation means the data hiding properties
// GETTERS and SETTERS are always public
// GETTERS and SETTERS are used to access the private variables from  the different class

private String names;

public void setNames(String names){
this.names = names;
}

public String getNames(){
return names;
}
}

------------------------------------------------------Class2----------------------------------------------------------

package package1;


public class Class2 {

public static void main(String[] args) {
Class1 c1 = new Class1();
c1.setNames("bpn@gmail.com"); // Set the name inside inside the variables
String e=c1.getNames(); 
                                             // get the name from the variables and put it into the string and the print

System.out.println(e); 
}
}

----------------------------------Another Way--------------------------------------------------------

package package1;

//Using constructors

public class AnotherWay {

private String names;

public AnotherWay(String names) {
this.names = names;
}
public String getNames(){
return names;
}
}

No comments:

Post a Comment