getters and setters java code example

Example 1: creating an object from the getter of a different class

class Example():
    def __init__(self):
        self.test = 25

    def getTest(self):
        print(self.test)


class Example2():
    def createObject(self):
        return Example()

abc = Example2() #abc is an object created from the Example2 class

xyz = abc.createObject() #xyz is an obejct of the Example class

xyz.getTest() # this outputs 25

Example 2: java get set

class Employ
{
  public String name;						//name of the employ
  
  public String getName()					//Get the name
  {
    return name;
  }
  
  public String setName(String newName)		//Set the name
  {
    this.name = newName;
  }
}

Example 3: 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 4: java setter

public setValue(value) {
  this.value = value;
}

Example 5: setter&getter java

public class Vehicle {
  private String color;
  
  // Getter
  public String getColor() {
    return color;
  }
  
  // Setter
  public void setColor(String c) {
    this.color = c;
  }
}

Example 6: java getter

public getValue() {
  return value;
}

Tags:

Html Example