Tuesday, 12 December 2017

Object Oriented Programming(OOP) Explained with Java Examples (Part 4)

In this lesson we would examine the abstract keyword, how to use it and when to use it.
What is Static Keyword
The static keyword is used when the method or variable is to be shared by  all instances on the class.

Static Variable
When a variable is marked as static, it means that you can no longer make new copies of that variable. You only have one copy. So anywhere in your program, when any object of the class modifies this variable, they would modify the very same variable.

Let's demonstrate this in Java using Netbeans
Step 1: Open Netbeans and create a class Animal with the following properties

private String name;
private String Type;
Static int NumberOfAnimals;
 
Step 2: Generate a constructor that takes all the three parameters

Static Variable or Class Variable
Note: When you are creating the constructor, you don't have option of using NumberOfAnimals because a static variable cannot be used as a parameter in the constructor.
This is why a static variable is also called a class variable because it belongs to the class and not to instances of the class. In this way, you don't have option of using it to create instances of the class.

Step 3: Generate the Getters and Setters
Note: When a variable is declared as static , then the generated Getter and Setter also become static. But they could also not be static.

If you have followed correctly, then your class would look like shown in the figure below:

We would test the use of static variables using the main program.

Step 4: Test the Program
Open the staticLesson.java file and inside the main function, create an animal object using the line of code below:

Animal myPet = new Animal("Nkita", "Dog");

myPet.SetNameOfAnimal("Koko");

myPet.SetType("Cat");

myPet.SetNumberOfAnimals(10);   //An instance cannot access a static variable

Animal.SetNumberOfAnimals(10);  //This works.

From the last line, we can see that static variables can only be accessed using the name of the class and not the instances.

What About Static Methods
The same applies for statics methods. In our example, the
  • getNumberOfAnimals()
  • setNumberOfAnimals()
are static methods. To call them you need to use the class name

Final Notes
A static Variable is also called a class variable just as a static method is also called a class method
An instance cannot access a static variable or method
To access a static variable or method, you need to use the name of the class.