Classes and Objects

Classes and Objects

·

9 min read

Class

  • A class is a blueprint or a template for creating objects.

  • It defines the structure and behaviour of objects that can be created based on it.

  • A class acts as a container for related data (variables) and functions (methods) that operate on that data.

  • It serves as a blueprint that describes the properties and behaviours that objects of that class will possess.

A class can have three types of variables:

  1. Local variables: These variables are defined inside methods, constructors, or blocks. They are used for temporary storage within the scope of the method or block. Local variables are declared and initialized within the method or block and are destroyed once the method or block has completed its execution.

  2. Instance variables: These variables are declared within a class but outside any method. They hold data specific to each instance of the class. Instance variables are initialized when an object of the class is created and can be accessed from any method, constructor, or block within that class.

  3. Class variables: These variables are declared within a class, outside any method, and marked with the static keyword. They are associated with the class itself rather than with any particular instance of the class. Class variables are shared among all instances of the class and can be accessed using the class name. They are initialized when the class is loaded and remain in memory throughout the execution of the program.

To summarize:

  • Local variables: Used for temporary storage within methods, constructors, or blocks.

  • Instance variables: Hold data specific to each instance of a class, accessible from any method, constructor, or block within the class.

  • Class variables: Associated with the class itself, shared among all instances of the class, and accessible using the class name.

Note : All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor. This default constructor calls the class parent’s no-argument constructor (as it contains only one statement i.e super();), or the Object class constructor if the class has no other parent (as the Object class is the parent of all classes either directly or indirectly).

Object

  • An object is an instance of a class.

  • It represents a specific entity or a real-world item that can be identified and manipulated in a program.

  • An object is created using the blueprint provided by its corresponding class.

  • Each object has its own set of attributes or variables that define its state. These variables are often referred to as instance variables or fields. The state of an object can change over time.

  • In Java, objects are accessed through references rather than directly. A reference is a variable that holds the memory address of an object. It allows us to interact with and manipulate the object.

  • Objects can perform actions or behaviours. These behaviours are defined by methods, which are functions associated with the class. Methods allow objects to manipulate their state and interact with other objects.

Eg: Think of a class as a cookie cutter and an object as the cookie that is created when the cutter is used.

When you declare an object of a class, you are creating an instance of that class. Thus, a class is a logical construct. An object has physical reality. (That is, an object occupies space in memory.)

Example

Now let's consider a class called "Fruit" and an object of that class, which could be an apple.

A class can be compared to a recipe for making a fruit, and an object is the actual fruit that you create using that recipe.

For example:

Class: Fruit

Properties (characteristics): Color, Shape, Taste

Behaviours (actions): Eat, Cut, Juice

Now, let's create an object of the Fruit class, which is an apple:

Object: Apple

Properties (characteristics): Red color, Round shape, Sweet taste

Behaviours (actions): Eat, Cut, Juice

In this example, the Fruit class acts as a blueprint that defines the common properties and behaviours that any fruit can have. The object "Apple" is created using the Fruit class, and it possesses the specific characteristics and actions of an apple.

So, the class represents the general concept or template, while the object represents a specific instance or example of that concept.

Here's an actual Java code example of classes and objects using the Fruit analogy.

// The Fruit class serves as a blueprint for creating fruit objects
class Fruit {

    // Properties (characteristics) of a fruit
    String color;
    String shape;
    String taste;

    // Behaviors (actions) of a fruit
    void eat() {
        System.out.println("Eating the fruit...");
    }

    void cut() {
        System.out.println("Cutting the fruit...");
    }

    void juice() {
        System.out.println("Making juice from the fruit...");
    }
}

public class FruitExample {
    public static void main(String[] args) {

        // Creating an object of the Fruit class, representing an apple
        Fruit apple = new Fruit();

        // Setting the properties of the apple object
        apple.color = "Red";
        apple.shape = "Round";
        apple.taste = "Sweet";

        // Calling the behaviors of the apple object
        apple.eat(); // Outputs: Eating the fruit...
        apple.cut(); // Outputs: Cutting the fruit...
        apple.juice(); // Outputs: Making juice from the fruit...
    }
}

Syntax for creating Class

Let's explain the process of creating a class in Java:

To create a class in Java, we follow these steps:

  1. Declare the class: We start by declaring the class using the class keyword, followed by the class name. The class name should be meaningful and descriptive, indicating what the class represents.

     class ClassName {
    
     }
    
  2. Define class members: Inside the class, we define the members, which include variables (also known as fields) and methods. Variables represent the data or characteristics of objects, and methods define the behaviors or actions that objects can perform.

  3. Access modifiers: We can use access modifiers such as public, private, or protected to specify the visibility of class members. These modifiers determine which parts of the program can access the members.

  4. Instantiate objects: After creating the class, we can create objects (also called instances) based on that class.

Syntax for creating an Object

Here's the general syntax for creating an object:

ClassName objectName = new ClassName();

Let's break down the syntax:

  • ClassName: This is the name of the class for which we want to create an object. It specifies the type of the object we are creating.

  • objectName: This is the name we choose for the object variable. We use this variable to refer to the object and access its members (variables and methods).

  • new: The 'new' keyword is used to create objects and dynamically allocates memory for the object at runtime on the heap (a region of memory used for dynamic memory allocation). It ensures that the required memory is allocated to hold the object's properties and behaviors.

  • ClassName(): These parentheses indicate that we are calling the class's constructor to initialize the object. The constructor is a special method that is used to initialize the object's state.

In Java, the dot operator (.) is used to access the members (variables and methods) of an object. When we have an object, we can use the dot operator to refer to its specific variables or call its methods. It acts as a link between the object and its variables/methods.

To access instance variables and methods, you can follow these steps:

  1. Create an object of the class using the constructor:
ClassName objectReference = new ClassName();

Replace ClassName with the actual name of the class you're working with, and objectReference with a suitable variable name.

  1. Access an instance variable:

     objectReference.variableName;
    

    Replace ClassName with the actual name of the class and variableName with the name of the instance variable you want to access.

  2. Call the class method using the object reference and the method name:

     objectReference.methodName();
    

Replace methodName with the name of the method you want to call on the object and objectReference is a reference variable that holds the reference to an object of a particular class.

Memory Management

In Java, memory management is handled automatically by the Java Virtual Machine (JVM). When we create objects based on a class, memory is allocated for those objects dynamically at runtime.

When a class is loaded by the JVM, memory is allocated to hold the class's code (methods, variables, etc.) in a specific area called the "Method Area" or "Class Area." This memory is shared among all instances (objects) of that class.

For each object created based on the class, additional memory is allocated in a different area known as the "Heap". The heap is a region of memory used for dynamic memory allocation. It is where objects are stored and managed during the program's execution.

Each object in the heap consists of two parts: the object's data (instance variables or fields) and a reference to the class's code in the method area.

When we use the "new" keyword to create an object, the JVM determines the amount of memory needed to hold the object's data based on the class's definition. It then allocates the required memory on the heap.

The JVM keeps track of allocated memory and automatically performs memory management tasks, including memory allocation and deallocation (releasing memory that is no longer needed).

Java employs a garbage collector, which periodically identifies objects that are no longer reachable or referenced by the program. These objects are considered eligible for garbage collection. The garbage collector reclaims the memory occupied by these objects, making it available for future allocations.

The garbage collector follows different algorithms (such as mark-and-sweep, generational, or concurrent) to efficiently identify and collect garbage objects.

One of the advantages of Java's automatic memory management is that it helps developers avoid memory leaks and manual memory deallocation, reducing the risk of memory-related bugs.

However, it's important to note that while Java handles memory management automatically, it's still essential to write efficient and optimized code. For example, avoiding unnecessary object creations or ensuring timely release of resources (such as closing file handles) can help improve memory usage and overall performance.

Naming Conventions

The naming conventions for classes and objects follow certain guidelines. Here's how the names of classes and objects are typically formatted:

  1. Class names: Class names should begin with an uppercase letter and use camel case. Camel case means that if the name consists of multiple words, each word except the first one starts with an uppercase letter, without any spaces or underscores. For example: MyClass, Car, StudentRecord.

  2. Object names: Object names should begin with a lowercase letter and use camel case as well. Again, camel case means that if the name consists of multiple words, each word except the first one starts with an uppercase letter, without any spaces or underscores. For example: myObject, carInstance, studentRecord.

We appreciate your interest in Class & Object and hope this post has been helpful to you. If you have any further questions or feedback, please feel free to reach out to us. Thank you for reading!

Did you find this article valuable?

Support Codies Coder by becoming a sponsor. Any amount is appreciated!