Classes and Objects in Java

Java is an object oriented programing language. In Java every entity is identified by an object. For example a bus is an object, it has fetures like speed , capacity etc. It has well defined ways to set the speed or to stop the bus.

Classes are blue-prints of objects. All objects are derived from some class. A class defines properties and methods which are inherited by all the objects of that class. In short :

A class defines a new data type. Once it is defined it can be used to define new objects of that type.

1. Syntax for class declaration

A class must be declared before it is used to create objects. A class contains:

  • Variables : They store the state of an object. They can be of three types :
    • Instance variables : Every object of the class has its own copy of instance variabels.
    • Class variables : A class variable is shared by all the objects of a class.
    • Local variables : A variable declared inside a method or a code block.
  • Methods : They are the subroutines to manipulate the states of an object.

  • type and return_type refer to any data type.
  • parameter_list may be empty or a list of comma separated variable declarations.

Note: In general class names start with capital letters like Fruit , Flower etc.


2. Example : A Simple Class

Example below has a class named Bus. It has some variable and some methods to manipulate those variables.

Note a few things before you move :

  • Return type of methods that return nothing has been declared void.
  • Return type of methods that return something is decided by the data-type they return.


3. Declaring Objects of a class

Object declaration is a two step process:

  1. Reference variable creation : This variable doesn’t define the object. But it can refer to the object when it will be made.
  2. Object creation : Memory for an object is allocated and its reference is assigned to the reference variable. It is done using the new keyword and an appropriate constructor.

We will learn about constructor later but for time being consider it to be the classname followed by parentheses(like bus() constructor ).

These two steps can be merged as well.

 

Graphically these two steps can be visualized as :

Object creation is a two step process.
Object creation is a two step process.


4. Accessing members of an object

The data field of the object can be accessed using dot operator. But it is not advisible (you will know why, later). You should use methods to set the states of an object or to retrieve the state values.

  • To access the speed variable of object b1, you can use b1.speed.
  • You can also use getSpeed as b1.getSpeed() to get the value of speed.

Output :

 


5. Assigning Object reference to reference variables

Assignment operator works differently with object reference variables. Take the example below :

The new reference variable b2 refers the same object and no new object is created.

Graphically it can be visualized as :

Assigning reference of one variable to another only copies the reference and no new objects are made.
Assigning reference of one variable to another only copies the reference and no new objects are made.

 

So b1.color and b2.color both refer the same value. Lets test this:

Output :

When b2.color was set to Orange, b1.color also became orange as both b1 and b2 refer to the same object.


6. Variables

There are three types of variabels:

  1. Instance variables
  2. Class variables or static variables
  3. Local Variables

6.1 Instance Variables

  • Variables which belong to an instance of a class are called instance variables.
  • Every object has its own copy of the instance variables. So changing instance variables of one object has no effect on instance variables of other object.
  • By default all variables defined directly inside a class are instance variables. We don’t need any keyword to define them.

6.2 Class Variables

  • A variable which is shared by all instances of a class is called a class variable.
  • Since a class variable is shared by all instance of a class, modification of a class variable through one object of a class is visible through other objects as well.
  • We use static keyword to define a class variable. So they are also called static variables.

6.3 Local Variables

  • A variable defined inside a method or a block is called a local variable.
  • Every object has its own copy of its local variables just like instance variables.
  • We don’t need any keyword to define them.
  • They differ from instance variabels by the fact that instance variables are defined directly inside a class and local variables are defined inside methods and blocks of that class.

Lets have an example to understand them:

Output :

Notice few things here:

  • speed and color values for both of the objects are different. They are instance variables.
  • count value for both of them is same. It is because count variable is a class variable and is shared by both the objects. Initially it was set to 0 then c1.setAll() increased it to 1, again c2.setAll() increased it to 2.

7. Methods

Methods are ways to manipulate the states(variabels) of an object and to access the value of those states. The Syntax to declare a method is :

  • return_type can be any data type that the method returns. If a method doesn’t return anything then return type is set to void.
  • parameter_list is a list of comma separated variable declarations. If the method takes no arguments then it can be left empty as well.

Below is an example with different argument-list and return types:

Output :

It was a short discussion about methods. We will learn more about them in detail, in a separate chapter.


8. Setting the variables of an object.

Variables of an object can be set in a variety of ways.

  • Through constructors : At the time of object creation, variables can be initialized using constructors. Constructors can initialize a variable only once, at the time of object creation. Like :  Truck t = new Truck(120);
  • Through methods : As seen in examples above, methods are the most versatile ways to access and assign any variable. You can use them again and agian to set the variables. Like :   t.setColor("Green");
  • Direct variable access : Variable can be also accessed using reference variable name followed by dot operator followed by variable name. Like :  t.capacity = 20;
  • Assigning default value at the time of variable declaration :  You can give a default value to the variables when you are defining a class. All objects derived from that class will have the same value of those variables, if they are not modified in any other way. Like :  color = "Green";

Output :

Notice a few things about constructors:

  • They are like methods. They can take from 0 to a large number of arguments.
  • But they lack any return type. It is nothing, not even void.
  • They are actually object initializers. Using a constructor, you can set the initial values for instance variables at the time of object declaration.

9. Array of Objects

Like you know, a class defines a new data type. You can create an array of this data type as well. Take the example below:

Output :

 


10 Anatomy of a Java Source File

  • A file can have only one public class.
  • A file can have multiple non-public classes(private, protected etc.)
  • The name of the file should be the name of the public class followed by .java extension.
  • If the file is defined inside a package then the package statement must be the first line in your source file.
  • If you import any class then import statement must follow the package statement.

11. Miscellaneous Topics

You will learn about each of the sub-topics in detail as you move deeper into the tutorials. But for time being, let’s have a rough idea about some of them.

11.1 Packages in Java

Packages are ways to categorise the classes and interfaces of a java project. A package name translates to a folder name. When your project becomes large, it is advisible to group your classes in different packages to avoid name-conflicts.

11.2 Import Statement

Import statements allow you to import classes and interfaces written in differnet packages to the current scope.

11.3 Access Modifiers

Access modifiers control the visibility of the members of your class. It can be set to:

  • public : The methods and variables qualified as public are visible from anywhere in the project.
  • private : The methods and variables qualified as private are visible only inside the class.
  • protected : The methods and variables qualified as protected are visible inside their entire package and those subclasses that inherit them.
  • default(No access modifier) : The methods and variables qualified with nothing are visible from anywhere inside their package.

11.4 Garbage Collector and finalize() method

  • The memory for an object is allocated dynamically at run time on the heap(a section of main memory) area of the memory. When no reference to this object exists, this object is assumed to be not needed and memory occupied by this object is ready to be reclaimed.
  • You don’t have to worry about this. The Java Virtual Machine(JVM) automatically does this work for you.
  • This technique is called garabge collection. It is not fired when one or two objects go out of scope but when the JVM feels the need to do so.
  • finalize() method : Sometimes you would want some actions to be performed before the memory occupied by an object is reclaimed, like closing the file handles etc. You can achieve this by putting those actions inside a method named finalize(). The JVM calls this method on an object just beore the memory occupied by this object is reclaimed. Its general form is:

 


12. More to Learn

Classes offer a lot more vital concepts to make our life easier. To do justice to them they have been discussed in detail in separate chapters.

  • Constructors.
  • this keyword.
  • static keyword.
  • Innner classes and static Nested Classes.