Saturday, June 26, 2010

Creating Objects in Java

Here I'm going to show how to create objects in Java and how to use those objects with a simple Java code. The use of each line is described end of each line with comment(//).

class Family {

static String surname = "Mathiwes"; /* static variable so variable declarations(features) similar variable*/
double height; // instance variable

static void breathe() { // static method and methosds can be known as behaviors
System.out.println("Breathing");
}

void goToWork() { //instance method
double tempHeight = height + 0.1; // method local variable
}

public static void main(String[] args) {
Family father = new Family(); //Initialization of an Object
System.out.println(father.surname); //prints Silva
System.out.println(Family.surname); //prints Silva
System.out.println(father.height); //prints 0.0
father.height = 6.0; // variable initialization
System.out.println(father.height); //prints 6.0
father.breathe(); //method call and prints breathing
Family.breathe(); //method call and prints breathing
father.goToWork();//prints going to work
}

}

If you call a static variable or static method you can call it by the class name. But if you want to call a instance variable or method you have to create a an instance(means an object) of the class.

No comments:

Post a Comment