Classes and Objects in Java

Classes and Objects in Java
Classes and Objects in Java

Introduction

Classes and Objects are the backbones of Java. A class specifies the shape and nature of an object. It is the logical concept upon which the entire Java language is based.

Classes serve as the foundation for Java object-oriented programming. 

A class must encapsulate any concept we want to apply in a Java program. In this blog, we’ll be learning all the basic concepts of Classes and Objects in Java.

Let’s start with the classes in Java.

Classes in Java

A Class is a blueprint that defines new data types. This blueprint or prototype can then be used to create objects.  It is not a real-world entity. Hence it has no physical existence. In simple words, classes do not occupy memory space. 

We declare the exact form and nature of a class when we define it. Classes denote the collection of properties or methods that is common to all the objects of that class. This is accomplished by specifying the data it holds as well as the code that manipulates that data. 

Declaration of a Class in Java

The declaration of a class in Java includes the following components:

  • The keyword “class” is used in the class declaration. The first letter of the class name should be capitalized as per the convention.
  • Access modifiers such as public, private, etc. are placed before the class name. Classes in java containing the main method should be declared as “public”. 
  • The name of the superclass is followed by “extends” keywords (if any) for Inheritance
  • Similarly, we must provide a comma-separated list of interfaces implemented by the class followed by “implements” keywords(if any).
  • Body of the class enclosed in curly braces{}.
  • Even if we don’t explicitly specify one, every Java class has at least one “constructor. While declaring classes, constructors are optional. A brief description of constructors is mentioned in the latter part of this article.

A simple declaration of Java class is given below:

Access-modifiers class Classname extends A implements B,C
{
Attributes…
type instance-variable1;
type instance-variable2;
// …

Constructors…
Classname(parameter-list)
{
//body of the constructor
}

Methods...
type methodname1(parameter-list) 
{
// body of the method
}
type methodname2(parameter-list) 
{
// body of the method
}
// …
Main(optional)....
public static void main(String args[])
{
}
 }

Declaring Member Variables

  • The methods and variables defined inside a class are collectively referred to as members of the class
  • The instance variables and class variables are generally called Member variables.

Instance Variable:

A variable declared in a class but outside of constructors, methods, or blocks is an instance variable. When an object is instantiated, instance variables are created and are accessible to all constructors, methods, or blocks in the class. The instance variable can be given access modifiers, and each instantiated object of the class has a separate copy or instance.

Class Variable:

A class variable is any variable declared with the static modifier that has a single copy, regardless of the number of instances of the class.

blog banner 1

A class variable is not the same as an instance variable.

  • A Member variable declaration must include at least two components: the variable’s data type and its name.
type variableName;        // minimal member variable declaration
  • When we declare a Member variable, we can specify several other attributes for it, in addition to type and name, such as whether other objects can access the variable, whether the variable is a class or instance variable, and whether the variable is a constant.

Now let’s see an example of member variables declaration:

INSTANCE VARIABLECLASS VARIABLE
public class Product{public int Barcode; }public class Product{     public static int Barcode;}
  • We can provide an initial value for a field during declaration and can initialize in constructors as well. Remember, ‘Property’, ‘Instance variable’, ‘Field’, or ‘Attribute’ are the terms having the same meaning.

Example for both instance and class variables.

class VariableExample
{
    /* Below variable is Instance variable as it 
    is inside the class and outside the method
    declaration. It is not using STATIC 
    keyword and using default access modifier*/
    // Declaring Instance Variable
    int var1=5;
    int var2;
   
    /* Below variable is Class variable as it 
    is using STATIC keyword*/
    // Declaring Class Variable
    static int var3=625;
   
    //Constructor for VariableExample Class
    VariableExample(int num)
    {
        //Initialising Instance Variable in Constructor
        var2 = num;
    }
   
    //Method to display Instance Variables
    void printInstanceVariable()
    {
        System.out.println("Value of Instance Variable is "+var1);
        System.out.println("Value of Instance Variable initialized in Constructor is "+var2);
    }
   
}

public class Main
{
    public static void main(String args[])
    {
        //Creating object of VariableExample Class
        VariableExample ob1 = new VariableExample(25);

        //Calling printInstanceVariable() for each object
        ob1.printInstanceVariable();
       
        //Accessing Class Variable Outside Class using classname.variablename
        System.out.println("Value of Class Variable is "+VariableExample.var3);
    }
}

      Output:

Value of Instance Variable is 5
Value of Instance Variable initialized in Constructor is 25
Value of Class Variable is 625

Without further ado, let’s head on to Constructors in Java.

Constructors in Java

A constructor is a member function of a class, and its name is the same as the name of the class. When there is no constructor defined inside the class, the Java compiler provides a default constructor in the class. In Java, every class has a default constructor. 

The constructor has no return type. A constructor can be parameterized or overloaded. When we use the new keyword to create an object of a class, a constructor is invoked to initialize the data members of the class.

Example1: Consider this class below:

public class Bicycle 
{
 int gear; //instance variable
 int speed; //instance variable
    //Constructor 1
    public Bicycle(int startSpeed, int startGear) 
{
        gear = startGear;
        speed = startSpeed;
     }
    //Constructor 2
public Bicycle() 
{
   gear = 2;
   speed = 10;
}

}

The above class has one parameterized constructor. It creates space in memory for the object and initializes its fields. To create a new object called b1, a constructor is called by the new operator. 

Bicycle b1 = new Bicycle(30, 0, 8);

The Bicycle class has one no-argument constructor as well. We can create a new Bicycle object called b2 using this constructor.

Bicycle b2 = new Bicycle(); 

If we do not provide a constructor during class declaration, the compiler automatically provides a no-argument, default constructor.

Now, let’s learn about objects in detail.

The object of a Class

“A class can be visualized as a cookie cutter and objects as cookies. Unless we make cookies(Objects), there is no relevance to have a cookie-cutter(Class).”

A class is a blueprint for creating objects of type class. When we create an object of a class, we have created an instance of the class.

To learn and use Java, we have to identify three key characteristics of objects:

  • The behavior of the object – what can be done with the object?
  • The state of an Object – how will the object react when something is done?
  • The identity of an object – how will the object be distinguished from others?

Let’s start by looking at a simple example of a class. Here’s a class Rectangle that defines two instance variables: length and breadth. There are currently no methods in Rectangle.

class Rectangle
{
double length;
double breadth;
}
  • As mentioned earlier, a class defines a new type of data. In this case, the new data type is Rectangle.
  • It’s essential to keep in mind that declaring a class just creates a template. It does not create any physical entity(No memory allocation). 
  • Objects of type Rectangle are created as a result of the above code and these objects occupy memory.
  • To create an object of a class having physical existence, we have to write a statement like this:
Rectangle rec = new Rectangle(); // creates a Rectangle object called rec

All objects of the same class share a resemblance by having the same behavior. Now, let’s move to the creation of an object.

Object Creation:

Creating objects of a class is a two-step process.

  1. Declaring a variable of the class type. 
  • This variable is simply a variable that can refer to an object. 
  1. Acquiring an actual, physical copy of the object and assigning it to that variable. 
  • This can be done using the new operator.

The “new” operator:

The “new” operator dynamically allocates memory for an object and returns a reference to it. This reference is the address of the object allocated by new in memory. This reference is stored in the variable. In Java, all the objects of a class must be dynamically allocated. 

The general form of new:

class-var = new classname();

The diagrammatic representation of the new operator is given below:

New_Operator
New Operator

Let’s look at the detailed procedure of object creation.

In the above example, a line is used to declare an object of type Rectangle:

Rectangle rec = new Rectangle();

This statement is the combination of the two steps described above. It can be rewritten in two steps as follows:

Rectangle rec; // declare reference to object……………………….1
rec = new Rectangle(); // allocate a Rectangle object……………2
  • The first line declares rec as a reference to an object of type Rectangle. After this line executes, rec contains the value null, which indicates that it does not point to an actual object yet.
  • The second line allocates an actual object and assigns a reference to rec. After the second line executes, we can use rec as if it were a Rectangle object. But in reality, rec simply holds the memory address of the actual Rectangle object.

Example of class and Objects:

// A program that uses the Rectangle class.
class Rectangle
{
double length;
double breadth;
}

// This class declares an object of type Rectangle.

public class RectangleDemo 
{
public static void main(String args[]) 
{
Rectangle rec = new Rectangle();
double area;

// assign values to rec's instance variables

rec.length = 10;
rec.breadth = 20;

// compute area of Rectangle

area = rec.length * rec.breadth;
System.out.println("Area is " + area);
}
}

Output:

Area is 200.0
  • We should call the file that contains this program RectangleDemo.java, because the main( ) method is in this class. 
  • When we compile this program, two .class files will be created, one for Rectangle and one for RectangleDemo
  • The Java compiler automatically puts each class into its .class file. Both the Rectangle and the RectangleDemo class don’t need to be in the same source file. 
  • To run this program, we must execute RectangleDemo.class

Multiple objects of a class

Each object has its copy of the instance variables. This means that two objects of rectangle class have their separate copy of length and breadth. Changes in instance variables of one object do not affect the instance variables of another. 

For example, the following program declares two Rectangle objects:

// This program declares two Rectangle objects.
class Rectangle
{
double length;
double breadth;
}
public class RectangleDemo2 
{
public static void main(String args[]) 
{
Rectangle rec1 = new Rectangle();
Rectangle rec2 = new Rectangle();
double area;

// assign values to rec1's instance variables

rec1.length = 10;
rec1.breadth = 20;

// assign values to rec2's instance variables

rec2.length = 25;
rec2.breadth = 10;


// compute area of the first Rectangle

area = rec1.length * rec1.breadth;
System.out.println("Area1 is " + area);

// compute area of the second Rectangle

area = rec2.length * rec2.breadth;
System.out.println("Area2 is " + area);
}
}

Output:

Area1 is 200.0
Area2 is 250.0

The diagrammatic representation is as follows:

Multiple_objects_of_a_class
Diagrammatic representation

In the given figure, the object gets the memory in the heap area, and the reference variable, i.e. rec1 and rec2, gets memory in the stack area.

Creating multiple objects by one type only:

We can create more than the object by one type only as we do in primitive data types.

Rectangle r1=new Rectangle(),r2=new Rectangle();

Anonymous objects in Java

Anonymous simply means nameless. An object that has no reference is known as an anonymous object. If you have to use an object only once, an anonymous object is a good approach.

For example:

public class Calculation
{  
void fact(int  n)
{  
int fact=1;  
for(int i=1;i<=n;i++)
{  
fact=fact*i;  
   }  
System.out.println("factorial is "+fact);  
}  
public static void main(String args[])
{  
new Calculation().fact(5);
//calling method with anonymous object  
}  
}

Output:

factorial is 120

Let’s move to the frequently asked question related to classes and objects.

Frequently Asked Questions

What are classes and objects?

A class in Java is a blueprint from which objects are made. Objects are instances of type class.

What is the fundamental difference between classes and objects in Java?

A class is just a blueprint. It has no physical existence. Objects, on the other hand, are real-world entities having a physical existence.

What are classes and objects in oops?

Class and Objects are the backbones of every object-oriented programming language. All the code must be inside a class in a pure object-oriented language.

Is a class an object?

A class defines a new data type. This new type can then be used to create objects of that type.

What is an object, explain with an example?

An object is an instance of a type class. It is a real-world entity having a behaviour, state, and identity.

Key Takeaways

Classes and Objects are the basic building blocks of object-oriented programming languages like Java, C++, etc. This is an introductory blog including the fundamentals of classes and objects in Java.

To command the Java programming language, we suggest you practice problems on Code studio in Java language. 

Java is one of the most popular languages. It finds wide applications in Android development and server development. Learning Java in-depth will get you a lucrative placement. To learn more about Java, take a look at various resources offered by Coding Ninjas.

Happy Learning!