Aug 17, 2014

14. Static


We can use the static keyword to create class variables and methods. This means that that we do not need to create an instance object of the class with the new keyword.




We have two classes in our packages. The classes are in Ex14a.java and Ex14.java. The main() method is in the Ex14.java. In Ex14a.java, we create variables and methods that we will access within the main() method of Ex14.java.


// Ex14a.java
package com.javaAndroid.ex14;

public class Ex14a {
 int a = 1;
 static int b = 5;
 int reta() {
  return a;
 }
 static int retb() {
  return b;
 }
}



For variables defined in a class, outside the methods, we can have 4 different types of access. Three types of access use the keywords private, protected, or public. If it does not have any of those keywords, it is default access and has access to all the classes in the package.




A static method can be used with static variables. Since a static method exists even without instance of class objects, it would not make any sense for them to access non-static variables.


// Ex14.java
package com.javaAndroid.ex14;

public class Ex14 {
 public static void main(String[] args) {
  // instance of Ex14a
  Ex14a obja = new Ex14a();
  // Get instance variable
  System.out.println(obja.a);
  // static var should be accessed with class
  System.out.println(Ex14a.b);
  // and not with object
  System.out.println(obja.b); // warning
  // instance method
  System.out.println(obja.reta());
  // static method
  System.out.println(Ex14a.retb());
 }
}





No comments:

Post a Comment