setters getters javascript code example

Example 1: getters and setters javascript classes

// ES6 get and set
class Person {
  constructor(name) {
    this._name = name;
  }

  get name() {
    return this._name.toUpperCase();
  }

  set name(newName) {
    this._name = newName; // validation could be checked here such as only allowing non numerical values
  }

  walk() {
    console.log(this._name + ' is walking.');
  }
}

let bob = new Person('Bob');
console.log(bob.name); // Outputs 'BOB'

Example 2: getter and setters in js

var person={firstname:"chetha",secondname="kumar",get fullname()
{
  	return this.firstname+" "+this.secondname;
}
document.write(person.fullname);
var person={firstname:"chethan",secondname="kumar",course:"",set course(x)
{
  	this.course=x;
}
person.course="bca";
document.write(person.course);

Example 3: setters and getter best example

class Test {

  // private variables
  private int age;
  private String name;

  // initialize age
  public void setAge(int age) {
    this.age = age;
  }

  // initialize name
  public void setName(String name) {
    this.name = name;
  }

  // access age
  public int getAge() {
    return this.age;
  }

  // access name
  public String getName() {
    return this.name;
  }

}

class Main {
  public static void main(String[] args) {
    // create an object of Test
    Test test = new Test();

    // set value of private variables
    test.setAge(24);
    test.setName("Programiz");

    // get value of private variables
    System.out.println("Age: " + test.getAge());
    System.out.println("Name: " + test.getName());
  }
}