Classes and Objects in Java | Example Programs

In this tutorial, we will be familiar with basic concepts of classes and objects in Java with realtime examples.

We know that java is a true object-oriented programming language. In the object-oriented programming language, we design and develop an application program using classes and objects.

The underlying structure of all java programs is made up of classes. Anything we want to write in a java program must be encapsulated in a class.

A class is a model to create objects. It means that we write properties and actions of objects in the class.

Properties are represented by variables, and actions are represented by methods. So, a class consists of variables and methods.

In this chapter, we will know the following topics under classes and objects in Java. So, let’s understand one by one.

  • Objects in Java
  • Realtime examples of objects in Java
  • Classes in Java
  • Realtime examples of classes in Java
  • Declaration of class in Java
  • Components of class in Java
  • Flow of execution of program in Java
  • A simple programming structure of Java classes and objects.

Objects in Java

An object is a basic unit of an object-oriented programming language. It is any real-world thing that has properties and actions.

In other words, an entity that has state and behavior is known as object in Java. Here, the state represents properties and behavior represents actions or functionality.

For example, book, pen, pencil, TV, fridge, washing machine, mobile phone, etc. Objects in Java consists of states or attributes (called data members) and behavior (called methods).

An object is an instance of a class. Each instance of an object holds its own relevant data.

Characteristics of an object in Java

An object in Java has three characteristics:

1. State: State represents properties or attributes of an object. It is represented by instance variable. The properties of an object are important because the outcome of functions depends on the properties.

2. Behavior: Behavior represents functionality or actions. It is represented by methods in Java.

3. Identity: Identity represents the unique name of an object. It differentiates one object from the other. The unique name of an object is used to identify the object.

Let’s take a real-world example to understand all these points clearly.

Realtime Examples of Objects in Java

Realtime Example 1:

We are taking the example “person”. A person has three characteristics: Identity (name), State (properties), and behavior (actions or functionality). Look at the below figure.

Java object realtime example

In the above figure, a person is an object. First state of the person (object) is black hair which can be represented in Java like this: hairColor = “black”.

In the same way, second property of the object is eye color which can be represented in Java like eyeColor = “black” and so on. These are called attributes that define the properties of a person.

Let’s consider the behaviors or actions of a person. The actions of a person may be “eat, sleep, walk, play, and study”. We represent these actions in Java like this: eat(), sleep(), walk(), play(), and study(). These are called methods.

Thus, when properties and actions are combined together of any real-world object, make an object in Java.

Note: Noun in English represent properties or state of an object. It can be represented with the help of variables whereas verbs represent action/behavior which can be represented with the help of methods.

Realtime Example 2:

Let’s take one more interesting example ‘Phone Samsung Galaxy’. If I tell you to represent this phone in java in the form of an object then How will you do like that?

You can do that very easily. Ask two questions: What it has? (Properties)   and What it does? (Actions)

Properties are width = 6.2 or  “6.2 inch”, height = 13.6 or “13.6 cm”, color = “black”, OS = “Android”, price = 1000 or “1000$”, brand = “Samsung”, and weight = “130 gm”. All these are nouns called attributes in Java.

Actions/Behavior are call(), sendSms(), runApp(), browserInternet(), sharing(). Thus, a phone object is comprised of the properties that the phone has actions that phone does.

Realtime example 3:

Another example we can take “Pencil”. A pencil is an object. Its name is Natraj.

State: color is black.

Behavior: It is used to write. So, writing is behavior.

Thus, you can take any object around you and think about what property it has? and What action it does?

Classes in Java

A class in Java is a fundamental building block of object-oriented programming (OOP) language. In other words, a class is the basic unit of OOP.

According to OOPs concept in Java, a class is the blueprint/template of an object. It contains the similar types of objects having the same states (properties) and behavior.

In other words, a class can also be defined as “a class is a group of objects which are common to all objects of one type”.

Let’s understand it with some realtime examples.

Realtime Examples of Class in Java

Real-time example 1:

Let us consider two objects Samsung Galaxy S4 and iPhone. Suppose Samsung Galaxy S4 have some properties like width = “6.98 cms”, height = “13.6 cm”, OS = “Android”, brand = “Samsung”, price = “1000$” and actions are call(), sendMessage(), browser(), share().

Now, suppose iPhone has some properties such as width = “5.86 cm”, height = “12.3 cms”, OS = “iOS”, brand = “Apple”, price = “1200$” and actions are call(), sendMessage(), browse(), share().

Both objects have the similar properties and actions, but the type is the same “Phone”. This is the class. i.e the name of the class is “Phone”.

Realtime example 2:

Consider two different objects one boy and one girl. The boy has some properties like hairColor = “black”, eyeColor = “black”, skinColor = “Fair”, height = “5.10 inch”, weight = “65 kg” and actions are read(), play(), sleep(), walk().

A girl has some properties like hairColor = “brown”, eyeColor = “brown”, skinColor = “milky white”, height = “5.4 inch”, weight = “50 kg” and actions are read(), play(), sleep(), walk(). Here, the type of both boy and girl is the same. Type is “Person”. So, the class name is “Person”.

Realtime Example 3:

Suppose we create a class “Student” having probable attributes – student’s name, address, roll number and other related parameters.

So, students like John, Ricky, Deep, etc., will be the objects of a class Student having the same class members like student’s name, address, roll number, etc.

So, in short, we can say that a class is a group of objects having:

  • Similar properties
  • Similar behavior

In Java, there are different types of classes that exist in various packages. Some common type of class in Java is as follows:

  • Wrapper class
  • Mutable class
  • Abstract class
  • Final class
  • Anonymous class
  • String class
  • System class, etc.

A class is basically user-defined data types that act as a template for creating objects of the identical type. Every Java class contains attributes and methods. Attributes represent the state of a class. Methods (also known as functions) represent the behavior of a class.

Class Declaration in Java

A class can be declared using the keyword class followed by a class name. It has also a body within braces. The general syntax to declare a class in Java is shown below:

 modifierName class className
   // class body.

Components of Class in Java

In general, a class can have the following components to act as a template. It can be seen in the below figure and a brief explanation is given below.

Components of class in Java

1. Modifiers: A class can be either a public or default access modifier. But the members of class can be public, private, default, and protected. All these are the access modifiers.

2. Class name: By convention, a class name should begin with a capital letter and subsequent characters lowercased (for example Student).

If a name consists of multiple words, the first letter of each word should be uppercased ( for example CollegerStudent).

A class name can also start with an underscore ”_”. The following class name can be valid such as _, _Student. Keywords cannot be a valid class name. For example, class, true, null, etc are not accepted as a class name.

3. Body: Every class’s body is enclosed in a pair of left and right braces. In the body, a class can contain the following members.

class class_name 
 // Class body starts here.
 // Members of a class.
      1. Field declarations;
      2. Constructor declarations;
      3. Method declarations;
      4. Instance block declarations;
      5. Static block declarations;
 } Ends here.

If you are writing a simple program, everything must reside inside the body of the class. Let’s see in brief about all the members of the class.

Fields: Fields are data member variables of a class that stores data or value in it. It specifies the state or properties of the class and its object. It may be a local variable, instance variable, or static variable.

Constructor: A constructor is used to create an object. Every class must be at least one constructor otherwise, no object can be created of the class.

If you don’t explicitly define a constructor, the compiler automatically adds a default constructor inside the class. A constructor can be divided into two types, such as default constructor and user-defined constructor.

Method: A method defines an action or behavior of the class that a class’s object can perform. It has a body within braces. In the body, we write code that performs actions. It may be an instance method or a static method.

Block: A block is mostly used to change the default values of variables. It may be an instance block or static block.

Interface: An interface in Java is a mechanism that is used to achieve complete abstraction. It is basically a kind of class but can have only abstract method declarations and constants as members.

It is used to achieve multiple inheritances in Java. You will learn more details about the interface in the further tutorial.

Method main: A class has also the main method that provides the entry point to start the execution of any program. The main method is static in nature. The signature of the main method is as follows:

public static void main(String[] args) 
 //  This is a static region. 

The JVM executes everything between the curly braces { } of the main method. Every java program has at least one class and at least one main method.

Flow of Execution of Program in Java

1. Out of five elements declared inside the class body, the static variable, static block, and static method are executed first during the loading of the dot class file.

2. The instance variable is executed during object creation.

3. When the object is created, first, an instance block is executed before the execution of a constructor.

4. After the execution of an instance block, the constructor part will be executed.

5. After the execution of the constructor part, the instance method is executed.

6. The local variable is executed inside the method, constructor, or block.

A simple programming structure of Class and Objects in Java

Let’s understand a simple programming structure of class and objects in Java. Suppose, Student is a class name and the name, rollNo, id, age of student will be its properties. The “public” is the access modifier.

Let’s implement these properties in a Java program.

Program code:

public class Student 
// Declaration of state/Properties. 
    String name; // Instance variable. 
    int rollNo; // Instance variable. 
    int id; 
    static int age; // Static variable. 

// Declaration of constructor. 
      // Constructor body. 
// Declaration of Actions. 
    void display() // Instance method. 
       // method body. 
// Declaration of instance block. 
      // block body. 
public static void main(String[] args) 

Key points:

1. You can create any number of objects of a class.

2. The process of creating an object of a particular class is called instantiating of an object.

3. The object is called an instance of class.

Difference between Class and Object in Java

There are the following differences between class and object in java. They are as follows:

1. A class is a user-defined data type whereas an object is an instance of class data type.

2. A class generates objects whereas an object gives life to a class.

3. Classes do not occupy memory location but objects occupy memory location.

4. Classes cannot be manipulated due to not available in the memory location but objects can be manipulated.

Can we call Class as Data type in Java?

Yes, a class is also considered a user-defined data type. This is because a user creates a class.

Key Points concerning Classes and objects in Java

1. Objects, classes, data abstraction, encapsulation, inheritance, method overriding, polymorphism, and message passing are the fundamental terms and concepts to understand the concepts of object-oriented programming approach.

2. Objects are the basic runtime entities in object-oriented systems.

3. All objects in a system take a separate memory space independently of each other.

4. A class in OOPs represents a group of similar objects.

5. Once a class has been created, any number of objects belonging to that class can be created.

6. An object of a class is also known as an instance.

7. A class never represents an object, rather it represents data and actions that an object will have.

8. Members of a class consist of variables (data members) and methods (member functions).

In this tutorial, you learned about classes and objects in Java with realtime examples and basic programming structure. Hope that you will have understood all the basic points related to classes and objects in Java.

In the next tutorial, we will learn how to create an object of a class in java.

Thanks for reading!!!Next ⇒ How to create object in Java

⇐ Prev Next ⇒