Java Variable Static

Spread the love

(Extract from OCA Java SE 7 Programmer I Certification Guide Malagupta)


Class variables

A class variable is defined by using the keyword static. A class variable belongs to a

class, not to individual objects of the class. A class variable is shared across all objects—

objects don’t have a separate copy of the class variables.

You don’t even need an object to access a class variable. It can be accessed by using

the name of the class in which it’s defined:

package com.mobile;

class Phone {

           static boolean softKeyboard = true;

}

Let’s try to access this variable in another class:

package com.mobile;

class TestPhone {

           public static void main(String[] args) {

                      Phone.softKeyboard = false;
                      Phone p1 = new Phone();
                      Phone p2 = new Phone();
                      System.out.println(p1.softKeyboard); //print false
                      System.out.println(p2.softKeyboard); //print false
                      p1.softKeyboard = true;
                      System.out.println(p1.softKeyboard); //print true
                      System.out.println(p2.softKeyboard); //print true

           }
}

As you can see in the previous code, the class variable softKeyboard is accessible

using all of the following:

■ Phone.softKeyboard

■ p1.softKeyboard

■ p2.softKeyboard

Comments

comments

Leave a Reply