Java Class: static and non-static variables

We create 2 classes, Children and Child

 

Children.java

 

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package children;

/**
*
* @author dkenga
*/
public class Children {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//the variable name_of_school is static and can be
//accessed directly by the class.
//so, it belongs to the class, and not the object
//We do not need an object to access it.
String school = Child.name_of_school;
System.out.println(school);
//on the other hand, a non-static variable such as the
//age does not exists untill an object is created
//so, we need an object to access it as shown below
//Therefore Child.age cannot work
Child child = new Child();
int age_of_student = child.age;
System.out.println("age of child is " + age_of_student);

}
} 

Child.java

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package children;

/**
 *
 * @author dkenga
 */
public class Child {
    //data members
    //we declare a static variable/also called class variable
    //this variable exist even before an object is created. 
    //it can be access by the class name; no need of creating
    //an object. 
    static boolean hasHome = true;
    static String name_of_school = "Nairobi academy";
    //instance variable.
    int age = 7;
}

 

3 Comments

Add a Comment

Your email address will not be published. Required fields are marked *