getters setters java code example
Example 1: getters and setters javascript
let obj = {
log: ['a', 'b', 'c'],
get latest() {
if (this.log.length === 0) {
return undefined;
}
return this.log[this.log.length - 1];
}
};
obj.log.push('d');
console.log(obj.latest); //output: 'd'
Example 2: javascript getters and setters
/*Getter functions are meant to simply return (get) the value of an object's
private variable to the user without the user directly accessing the private
variable.*/
/*Setter functions are meant to modify (set) the value of an object's private
variable based on the value passed into the setter function. This change could
involve calculations, or even overwriting the previous value completely.*/
class Book {
constructor(author) {
this._author = author;
}
// getter
get writer() {
return this._author;
}
// setter
set writer(updatedAuthor) {
this._author = updatedAuthor;
}
}
const novel = new Book('anonymous');
console.log(novel.writer); // anonymous
novel.writer = 'newAuthor';
console.log(novel.writer); // newAuthor
Example 3: Getter and Setter methods
import java.util.Scanner;
class Student {
private String name;
private int age;
Student(){
this.name = "Rama";
this.age = 29;
}
Student(String name, int age){
this.name = name;
this.age = age;
}
public void display() {
System.out.println("name: "+this.name);
System.out.println("age: "+this.age);
}
}
public class AccessData{
public static void main(String args[]) {
//Reading values from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
System.out.println("Enter the age of the student: ");
int age = sc.nextInt();
Student obj1 = new Student(name, age);
obj1.display();
Student obj2 = new Student();
obj2.display();
}
}