Aug 18, 2014

18. Getters and Setters

Getters and Setters are often used to access private variables, these variables being visible to class where they are defined.




Once the private variables are declared, we can use the Generate Getters and Setters menu. This screenshot uses Eclipse. However, Netbeans has a similar menu option. We will use Netbeans later, as the jMonkey SDK is based on Netbeans.




Getters and Setters can have any access type, except private. It is usually public or default (no access keyword given). It can also be protected. We will cover protected later.


// Ex18.java
package com.javaAndroid.ex18;

public class Ex18 {
 private int a,b;
 private String s;
 public static void main(String[] args) {
  (new Ex18a()).ex18a();
 }
 // Getters and Setters
 public int getA() {
  return a;
 }
 public void setA(int a) {
  this.a = a;
 }
 public int getB() {
  return b;
 }
 public void setB(int b) {
  this.b = b;
 }
 public String getS() {
  return s;
 }
 public void setS(String s) {
  this.s = s;
 }
}



The main() method calls the method ex18a() in class Ex18a. Here the Getters and Setters are tested.


// Ex18a.java
package com.javaAndroid.ex18;

class Ex18a {
 void ex18a() {
  Ex18 o1 = new Ex18();
  o1.setA(5);
  o1.setB(10);
  o1.setS("Hello JavaWorld!");
  System.out.printf(" a = %d, b = %d, s = %s",
    o1.getA(),o1.getB(),o1.getS());
 }
}





No comments:

Post a Comment