Java Class Vs Object – How To Use Class And Object In Java

In this tutorial, we will discuss one of the OOPS concepts in detail. We will explore all about Java Class and Object along with examples:

We know that object-oriented programming emphasizes data and thus revolves around entities called objects. Classes act as blueprints of these objects.

Let us see how to create a class and its components. We will also learn to create & initialize objects in Java with the help of programming examples later in this tutorial.

=> Visit Here For The Exclusive Java Training Tutorial Series.

Class and Object in Java

Classes And Objects In Java

In Java, all features, attributes, methods, etc. are linked to classes and objects. We cannot write a Java program just with the main function without declaring a class the way we can do in C++.

For example, if we want to write a program on a vehicle, a vehicle is a real-time object. But vehicles can be of various types. This means that the vehicle has a type attribute that can assume various values like the car, truck, scooter, bike, etc.

So the way we express the vehicle object in Java is we create a class “Vehicle” and then define its various attributes. Then we can declare various Vehicle class objects like car, bike, etc.

Inside the class, we can define the properties of Vehicle as the class attributes (data members) and methods like startVehicle (), stopVehicle (), etc.

This way, to express even the smallest of the entity in Java, we need to first identify the object and then define its blueprint or a class.

So let’s first learn everything about classes and objects and then move on to the other concepts of OOP in Java.

Class In Java

To develop a program in Java, we make use of objects and classes. While a class in Java is only a logical unit, an object in Java is both a physical and logical entity.

What is an object in Java?

An object is an entity that has a state and exhibit behavior. For example, any real-life entity like a pen, a laptop, a mobile, a table, a chair, a car, etc. is an object. All these objects are either physical (tangible) or logical (intangible).

The intangible objects mostly are an airline system, banking system, etc. These are logical entities that have a particular state and behavior.

Every object has the following main characteristics:

  • Identity: A unique ID defines the object identity. This id is not seen by the normal user but internally JVM uses this ID to uniquely identify the object.
  • State: It defines the present data in the object or the value of the object.
  • Behavior: This feature represents the functionality (behavior) of an object. For example, the Vehicle object we discussed above has the behavior as start, stop, etc.

We will revisit the object definition when we define the class.

So what is a Class?

We know the main component of object-oriented programming is an object. If we want to build a specific type of object, we need a blueprint. This blueprint will provide us a set of instructions that will help us to build an object.

For example, let’s say we want to build a house. The house here is an object. To build a house we need an initial blueprint for the house. We cannot go about directly building the house as we please.

This is where class comes into the picture. So to build an object or real-life entity, we will first have a blueprint that determines the contents and behavior of an object. This is known as a class in object-oriented programming.

So a class can be defined as “a blueprint or a template and it defines the state and behavior of the object”.

We can also view the class as a group of objects. This group has some properties that are common among all the objects.

Let’s see how to create a class in Java.

How To Create A Class In Java

The general class syntax of a class definition in Java is:

<access_modifier> class <class_name> extends <superclass> implements interface_name> {
//fields;
//constructors
//methods;
//blocks
}

The above general declaration of a class is represented in the below diagram with an example class declaration:

class declaration

Note that superclass and interface in the class declaration are optional. We can choose to have a standalone class without extending it from another superclass or implementing any interface.

The above general definition also showed the components that can be present in the class definition.

Components Of Class

The Components of Class are represented below.

Components of a class

As shown in the above diagram, a Java class contains the following components:

  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested class and interface

We will discuss the first three components next. These components are required in any class. Nested classes and interfaces are a different topic altogether and will be discussed in our later tutorials.

Before we begin a discussion on class components, let’s first define a class Customer_Account

class Customer_Account 
{  
	static String bank_name;	//class variable
	long customer_accountNo;         //instance variable
	String customer_name;  	//instance variable
	//constructor
	Customer_Account (long accountnum, String accName){
		customer_accountNo = accountnum;
     		customer_name = accName;
 	}
	//method
 	void printInfo(){
    	   	 System.out.println ("Customer Account Details:");
    		System.out.println ("Customer Account Number: " +  customer_accountNo);
   		 System.out.println (" Customer Name: "+customer_name);  
	}  
}

Fields

Fields are variables or data of the class. Fields are also called as member variables in Java. We use the terms field and variable interchangeably.

Usually, Fields of a class are of two types:

#1) Class Variables: Class variables are declared with the word “static” so that they are static variables. This means that this type of variable has only one copy per class, irrespective of how many instances or objects are present for that class.

#2) Instance Variables: These are the opposite of class variables. The data members are called instance variables because these variables have separate memory allocated for them for each class instance at runtime.

In the above class definition, we have shown both class and instance variables. The variable “bank_name” declared with a static modifier is the class variable. The other two variables “customer_accNo” and “customer_name” are instance variables.

Constructor

Constructors are special methods that are generally used to initialize an instance of a class. Constructors do not have a return type, they have the same name as the class, and may or may not contain parameters.

In the above class definition, we have one constructor.

Customer_Account (long accountnum, String accName)

We will learn more about constructors in our subsequent tutorials.

Method

A method in a Java class is the function that defines the behavior of the object and its members.

A class method is created in the same way in which we create regular methods in a program. Inside the class method, we can use all the constructs and features provided by Java.

In our example class definition, we have a “printInfo” method that displays the various data members of the class.

A Java class method usually has the following prototype:

<access_modifier> <return_type> method_name(parameter list…){
			//code blocks
		}

Class methods are accessed by the class instance using the dot operator. So if we create an instance acc of the above class “Customer_Account” then we can access printInfo using the below code line.

            acc.printInfo();

If the access_modifier is static, then we do not need an instance to access the method. We can use the class name directly to access the method as,

Custome_Account.printInfo ();

Java Class Example

Let’s implement a simple example to demonstrate a Class and Object in Java.

//declare a class with three data members
class Student{  
 int student_id;  
 String student_name;
 Double student_marks;
}  
  
class Main{  
 public static void main(String args[]){  
  //create a Student object using new operator
  Student student_object = new Student();  
  //display data members of the class.
  System.out.println("Student Id:" + student_object.student_id);  
  System.out.println("Student Name:" + student_object.student_name);  
  System.out.println("Student Marks:" + student_object.student_marks);
     
 }  
}  

Output

OUTPUT - Class example

The above program declares a Student class. It has three instance variables, viz. student_id, student_name, and student_marks.

Then we define the Main class, in which we declare an object of Student class named student_object. Then using the dot operator, we access the instance variables and print their values.

The above program is an example of a main method outside the class.

In the below example we will have a main method within the class.

//declare a class with three data members
class Student{  
 int student_id;  
 String student_name;
 Double student_marks;

 public static void main(String args[]){  
  //create a Student object using new operator
  Student student_object = new Student();  
  //display data members of the class.
  System.out.println("Student Id:" + student_object.student_id);  
  System.out.println("Student Name:" + student_object.student_name);  
  System.out.println("Student Marks:" + student_object.student_marks);
     
 }  
}  

Output

output - main method within the class

The above program is the same as the previous program except that the main method is within the Student class.

Object In Java

Now, we have enough knowledge about classes in Java, we can redefine the object in terms of class. So an object is “an instance of a class”. Thus we create a variable or instance of type class_name and it is termed as an object.

Some points to remember about an object:

  • An object is seen as a basic unit of OOP along with the class.
  • An object is a runtime unit.
  • An object is termed as an instance of a class.
  • An object has behavior and state.
  • An object takes all the properties and attributes of the class of which it is an instance. But at any point, each object has different states or variable values.
  • An object is used to represent a real-time entity in software applications.
  • A single class can have any number of objects.
  • Objects interact with each other by way of invoking methods.

How To Instantiate An Object 

Declaration of the object is also termed as an instantiation of objects in Java. The declaration of an object is the same as declaring a variable.

For example, the Customer_Account class that we have declared above can be used to declare an object.

Thus we declare or instantiate the object of Customer_Account as follows:

Customer_Account account;

The above statement declares or instantiates an object named ‘account’ of the Customer_Account class.

Note that when we instantiate an object of a class, the class should strictly be a “concrete class”. We cannot declare an object of an abstract class.

The above statement only declares an object. We cannot use this variable to call methods of the class or set values of the member variables. This is because we have not allocated any memory for the declared object.

So we have to properly create an object to use it further.

The actual creation of an object is done by the initialization of objects. Once we declare an object, we need to initialize it. Then only we can use this object to access the member variables and methods of the class.

How To Create An Object

We can create an object in Java using the following methods:

#1) Using A New Keyword

We can initialize an object by using a new keyword. This method is the most commonly used method to create a new object.

For example, given a class ABC, we can create a new class object as follows:

ABC myObj = new ABC ();

In the above statement, myObj is the new object created using the new operator. The object created using this method has the initial values of all the data members. The construct ABC () following the new keyword is the default constructor of the class ABC.

We can also define constructors with parameters and call that constructor with the new keyword so that we create an object with the desired values of data members.

#2) Using Class.forName() Method

Java provides a class named “Class” which keeps all the information about classes and objects in the system. We can use the forName () method of the ‘Class’ class to create an object. We have to pass a fully qualified class name as an argument to the forName method.

Then we can call the newInstance () method that will return the instance of the class.

The following code lines show this.

ABC myObj = Class.forName (“com.myPackage.ABC”).newInstance();

The above statement will create a new object myObj of class ABC.

#3) By clone() Method

Object class in Java provides a clone () method that returns the clone or copy of the object passed as an argument to the clone () method.

For example,

ABC myobj1 = new ABC ();

ABC testObj = (ABC) myobj1.clone ();

#4) By Deserialization

Java provides a technique called deserialization wherein we read an object from a saved file. We will be learning deserialization in a separate tutorial.

How To Initialize An Object

In this section, we will discuss the methods to initialize an object in Java. Initialization refers to assigning values to data members of the class. Given below are some of the methods that are used to initialize objects in Java.

#1) Initialize an Object through a Reference

The reference object created is used to store values in the object. This is done simply by using an assignment operator.

The initialization of an object by using reference is shown in the program below.

//declare a class with three data members
class Student{  
 int student_id;  
 String student_name;
 Double student_marks;
}  
  
class Main{  
 public static void main(String args[]){  
  //create a Student object using new operator
  Student student_object = new Student();  
  //initialization of class members using reference
  student_object.student_id = 101;
  student_object.student_name = "Elena";
  student_object.student_marks = 89.93;
  //display data members of the class.
  System.out.println("Student Id:" + student_object.student_id);  
  System.out.println("Student Name:" + student_object.student_name);  
  System.out.println("Student Marks:" + student_object.student_marks);
     
 }
}  

Output

output - Initialize an object through a reference

The above program declares a Student class with three-member variables. Then in the main method, we create an object of Student class using the new keyword. Then we assign data to each of the member fields of the object as shown in the program.

#2) Initialization of Object through Method

In this example, we are creating the two objects of the Student class and initializing the value to these objects by invoking the insertRecord method. The method insertRecord is a member method of the class Student.

//declare a class with three data members
class Student{  
 int student_id;  
 String student_name;
 Double student_marks;
 //method to initialize class data members
 void initialize_object(int id, String name, double marks)
 {
     student_id = id;
     student_name = name;
     student_marks = marks;
 }
}  
  
class Main{  
 public static void main(String args[]){  
  //create a Student object using new operator
  Student student_object = new Student();  
  //initialization of class members through method
  student_object.initialize_object(27, "Stefan", 78.86);
  //display data members of the class.
  System.out.println("Student Id:" + student_object.student_id);  
  System.out.println("Student Name:" + student_object.student_name);  
  System.out.println("Student Marks:" + student_object.student_marks);
     
 }  
}  

Output

output - Initialization of the Object through Method

#3) Initialization of Object through Constructor

We can also initialize an object by using a constructor.

The program to demonstrate the use of constructor is given below.

//declare a class with three data members
class Student{  
 int student_id;  
 String student_name;
 Double student_marks;
 //constructor for initialization
 Student(int id, String name, double marks)
 {
     student_id = id;
     student_name = name;
     student_marks = marks;
 }
}  
  
class Main{  
 public static void main(String args[]){  
  //create a Student object using new operator and initialize it with constructor
  Student student_object = new Student(27, "Stefan", 78.86);  
  //display data members of the class.
  System.out.println("Student Id:" + student_object.student_id);  
  System.out.println("Student Name:" + student_object.student_name);  
  System.out.println("Student Marks:" + student_object.student_marks);
     
 }  
}  

Output

output - Initialization of Object through Constructor

In this program, the` Student class has a parameterized constructor that takes the parameters and assigns them to the member variables.

Class Vs Object In Java

ClassObject
Class is a template or a blueprint for object creation.The object is an instance of a class.
The class does not allocate any memory when created.The object is allocated memory when created.
The class is a logical entity.The object is a physical entity.
Class is declared using a class keyword.Object is created using new, forName ().newInstance () , clone() methods.
Class is a group of identical objects. E.g. Class Animals ().Object is a specific entity. E.g. Animals dog = new Animals ();
The class can be declared only once.A class can have any number of instances or objects.
A class member field doesn’t have any values.Every object has a copy of member fields and their associated values.

Frequently Asked Questions

Q #1) What is the difference between Class and Object?

Answer: A class is a template used for the creation of objects. An object is an instance of a class. While a class is a logical entity, an object is a physical entity. Each object has a state in which all the member variables have specific values. The class does not have a state.

Q #2) What does a Java class contain?

Answer: A Java class that acts as a template or a blueprint for creating objects defines properties or fields and behaviors or methods.

Q #3) Why do we use Classes in Java?

Answer: Using classes and objects we can model the real-world applications in Java and thus solve them efficiently. Objects with a state and behavior represent real-world entities and classes act as their blueprints. Hence by using classes as building blocks we can model any complex application.

Q #4) Explain class and object with a real-life example.

Answer: If we take the car as an object then a car can have attributes like make, color, engine, mileage, etc. It can also have some methods like start (), stop (), applybrakes (). Thus we can model a car into a software object. Now the car can have various makes like Maruti, fiat, etc.

So to represent all these car models, we can have a class template that will contain all the common attributes and methods defined so that we can instantiate this class and get our desired car object.

Thus a real-life object car can be easily converted into an object in Java.

Conclusion

In this tutorial, we have learned the details of classes and objects in Java. We covered the definition of class and object. The tutorial has a detailed discussion on defining the class, components of the class, as well as the examples of how to use class in a program.

We also learned the details of objects in Java including its declaration, creation, initialization, etc. with appropriate programming examples.

We explored the main differences between class and objects. In our next tutorials, we will discuss the types of classes and the constructors in class following which we will move onto other topics.

=> Watch Out The Simple Java Training Series Here.