Thursday, May 31, 2018

Java Concepts[1]-Classes and Objects

Hi, I’m going to explain important basic java concepts in an easy way using simple and real-life examples.

First I’m going to explain you about java classes and objects.

Class is a user defined blueprint/template that describes the behavior/state the object of its type.

Object is an instance of a class. It consists of states and behavior. 

We’ll take Human class
States ➝ Variables/Fields
Behaviors   ➝    Methods


Following is an example of how to code the above scenario in Java.


#tip 1- Class name should be a noun/nouns and the first letter should be upper case. If there is more than one noun, first letter of each word should be capitalized. (ex. Human, TwoWheelVehicle)

#tip 2- Method name should be a verb and should start with a lower case letter. When there is more than one, the first letter should be lower case with the first letter of internal words capitalized. (Ex-eat, getName)

#tip 3-Variable names should start with a lower case letter. (name, firstName)
           
           There are 3 types of variables.
           1.Local Variables- Variables that declared inside the method. These variables can be used only within that method.

                                                 

            2.Instance Variables-Variable that declared inside a class but outside any method. These variables are initialized when the class is instantiated. These variables can be accessed from inside any method, constructor or blocks of that particular class.



           3.class variables- Variables declared inside a class but outside any method with the static keyword. There is only one copy of this variable that is shared with all instances of that class.

                               


Illustration on instance variables and class variables
'noHumans' is a static variable. So it is stored inside the Class memory and common to all objects. 'name', 'age' and 'weight' are instance variables and they are stored inside the object memory. So each object will have its own copy of instance variables




#tip 4- Every class has a constructor. Constructors should have the same name as the class. A class can have more than one constructor


I hope you understood the classes and objects of Java clearly. If you need more clarification on anything please feel free to leave a comment

Thank You.

Sahani Perera

3 comments: