Understanding Classes and Objects in Java

Understanding Classes and Objects in Java

Confused between Objects and Classes no worries!!!!! This article will clear all the concepts of Objects and Classes.

Java, being and Object-Oriented Programming language, revolves around the concept of classes and objects. If you’re new to Java, understanding these concepts us fundamental to writing efficient and objects, how they interact, and how you can use the, effectively.

What is a class?

A class in Java is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects created from the class will have. Think of a class as a plan for building something—it describes what the finished product will look like and how it will behave.

Syntax of a class:-

class ClassName {
    // Fields (Attributes)
    dataType fieldName;

    // Methods (Behaviors)
    returnType methodName(parameters) {
        // method body
    }
}

For example, consider a class representing a car:-

 class Car {
    // Attributes (fields)
    private String make;
    private String model;
    private int year;
    private double mileage;

    // Constructor
    public Car(String make, String model, int year, double mileage) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.mileage = mileage;
    }

    // Method to display car details
    public void displayDetails() {
        System.out.println("Car Make: " + make);
        System.out.println("Car Model: " + model);
        System.out.println("Year: " + year);
        System.out.println("Mileage: " + mileage + " miles");
    }

    // Method to update mileage
    public void updateMileage(double newMileage) {
        if (newMileage > mileage) {
            mileage = newMileage;
            System.out.println("Mileage updated to: " + mileage + " miles");
        } else {
            System.out.println("New mileage must be greater than current mileage.");
        }
    }

    // Getters
    public String getMake() {
        return make;
    }

    public String getModel() {
        return model;
    }

    public int getYear() {
        return year;
    }

    public double getMileage() {
        return mileage;
    }
}
public class main {
    public static void main(String[] args) {
        // Create a new Car object
        Car myCar = new Car("Toyota", "Camry", 2020, 15000);

        // Display car details
        myCar.displayDetails();

        // Update mileage
        myCar.updateMileage(16000);

        // Attempt to update mileage with a lower value
        myCar.updateMileage(15500);
    }
}

What is an Object?

An object is an instance of a class. When you create an object, you are creating a specific realization of the class template. Objects hold specific values for the properties defined in the class and can perform the behaviors described by the class’s methods.

Creating an Object:-

To create an object, you use the new keyword:

ClassName objectName = new ClassName();

For the car class, we can create objects like this:

Car myCar = new Car("Toyota", "Red", 2020);
Car yourCar = new Car("Honda", "Blue", 2018);

Accessing Object Attributes and Methods

You can access an object’s attributes and methods using the dot operator (.)::

System.out.println(myCar.brand); // Outputs: Toyota
myCar.drive(); // Outputs: Toyota is driving.

Example:-

 class Car {
    // Attributes (fields)
    private String make;
    private String model;
    private int year;
    private double mileage;

    // Constructor
    public Car(String make, String model, int year, double mileage) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.mileage = mileage;
    }

    // Method to display car details
    public void displayDetails() {
        System.out.println("Car Make: " + make);
        System.out.println("Car Model: " + model);
        System.out.println("Year: " + year);
        System.out.println("Mileage: " + mileage + " miles");
    }

    // Method to update mileage
    public void updateMileage(double newMileage) {
        if (newMileage > mileage) {
            mileage = newMileage;
            System.out.println("Mileage updated to: " + mileage + " miles");
        } else {
            System.out.println("New mileage must be greater than current mileage.");
        }
    }

    // Getters
    public String getMake() {
        return make;
    }

    public String getModel() {
        return model;
    }

    public int getYear() {
        return year;
    }

    public double getMileage() {
        return mileage;
    }
}
public class main {
    public static void main(String[] args) {
        // Create a new Car object
        Car myCar = new Car("Toyota", "Camry", 2020, 15000);

        // Display car details
        myCar.displayDetails();

        // Update mileage
        myCar.updateMileage(16000);



    }
}

Characteristics of Objects:-

  1. State:- The state of an object is represented by its attributes (also known as fields or properties). For example, in a Car object, the state might include properties like make, model, year, and mileage.

  2. Behavior:- The behavior of an object is defined by its methods (functions). These methods can manipulate the object's state or perform actions. For example, a Car object might have methods like drive(), refuel(), or updateMileage().

  3. Identity:- Each object has a unique identity, which distinguishes it from other objects, even if they have the same state. In Java, this identity is typically represented by the object's memory address.

Important concepts of Classes and Objects

  1. Fields and Methods

Fields are variables that store data for an object, while methods define the behaviors an object can perform. Together, they define the structure and functionality of a class.

  1. Constructors

Constructors are special methods used to initialize objects. A constructor has the same name as the class and does not have a return type. In the Car example, the constructor initializes the brand, color, and year attributes.

  1. Encapsulation

Encapsulation is the principle of bundling data (fields) and methods into a single unit (class) and restricting direct access to some components. You can achieve encapsulation by declaring fields as private and providing public getter and setter methods.

  1. Inheritance and Polymorphism

Inheritance allows a class to acquire the properties and methods of another class. Polymorphism enables methods to behave differently based on the object that calls them. While these concepts go beyond basic classes and objects, they highlight the power of Java’s object-oriented model.

Real World Example

class BankAccount {
    // Attributes
    private String accountHolder;
    private double balance;

    // Constructor
    public BankAccount(String accountHolder, double initialBalance) {
        this.accountHolder = accountHolder;
        this.balance = initialBalance;
    }

    // Methods
    public void deposit(double amount) {
        balance += amount;
        System.out.println("Deposited " + amount + ". New balance: " + balance);
    }

    public void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
            System.out.println("Withdrew " + amount + ". Remaining balance: " + balance);
        } else {
            System.out.println("Insufficient funds.");
        }
    }

    public double getBalance() {
        return balance;
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an object
        BankAccount myAccount = new BankAccount("John Doe", 500.00);

        // Using the object
        myAccount.deposit(200.00);
        myAccount.withdraw(100.00);
        System.out.println("Final balance: " + myAccount.getBalance());
    }
}

Conclusion

Classes and objects form the backbone of Java programming. By understanding how to define classes, create objects, and leverage object-oriented principles like encapsulation, you can design robust and reusable code. Practice creating your own classes and objects to deepen your understanding of these essential concepts!