Basic Understanding Of Object Oriented In Java

Object-Oriented Programming (OOP) in Java is a programming paradigm that organizes code into objects, which are instances of classes. While OOP is often associated with concepts like encapsulation, polymorphism, inheritance, and abstraction, it’s possible to explore the foundational aspects of OOP without delving into these principles. This blog focuses on the core ideas of OOP in Java—classes, objects, and basic class design—while providing detailed explanations and example programs to clarify concepts.

What is Object-Oriented Programming?

OOP is a way to structure programs by modeling real-world entities as objects. In Java, objects are created from classes, which act as blueprints defining the properties (data) and behaviors (methods) of objects. The key focus here is on creating and using classes and objects to organize code in a modular and reusable way.

Without encapsulation, polymorphism, inheritance, or abstraction, we’ll concentrate on:

  • Defining classes and creating objects.

  • Adding attributes (fields) and behaviors (methods) to classes.

  • Instantiating objects and interacting with them.

  • Writing simple programs to demonstrate these concepts.

Core Concepts of OOP in Java

1. Classes

A class is a template or blueprint for creating objects. It defines:

  • Fields (variables) to store data.

  • Methods to define behaviors or actions.

Syntax for Defining a Class:

class ClassName {
    // Fields (variables)
    int fieldName;

    // Methods
    void methodName() {
        // Code for behavior
    }
}

2. Objects

An object is an instance of a class. You create an object using the new keyword, and it represents a specific entity based on the class blueprint.

Creating an Object:

ClassName objectName = new ClassName();

3. Fields and Methods

  • Fields: Variables defined in a class that hold the state or data of an object.

  • Methods: Functions defined in a class that describe what an object can do.

Example Program 1: Creating a Simple Student Class

Let’s create a program to model a Student class with fields for name and roll number, and methods to set and display this information.

class Student {
    // Fields
    String name;
    int rollNumber;

    // Method to set student details
    void setDetails(String studentName, int roll) {
        name = studentName;
        rollNumber = roll;
    }

    // Method to display student details
    void displayDetails() {
        System.out.println("Student Name: " + name);
        System.out.println("Roll Number: " + rollNumber);
    }
}

class Main {
    public static void main(String[] args) {
        // Creating an object of Student
        Student student1 = new Student();

        // Setting details for student1
        student1.setDetails("Alice", 101);

        // Displaying details
        student1.displayDetails();
    }
}

Output:

Student Name: Alice
Roll Number: 101

Explanation:

  • The Student class has two fields: name (String) and rollNumber (int).

  • The setDetails method assigns values to these fields.

  • The displayDetails method prints the field values.

  • In the Main class, we create a student1 object, set its details, and display them.

This program demonstrates how to define a class, create an object, and use methods to interact with the object’s data.

Example Program 2: Modeling a Car Class

Let’s create another program to model a Car class with fields for brand and speed, and methods to initialize and update the speed.

class Car {
    // Fields
    String brand;
    int speed;

    // Method to initialize car details
    void initialize(String carBrand, int initialSpeed) {
        brand = carBrand;
        speed = initialSpeed;
    }

    // Method to increase speed
    void increaseSpeed(int increment) {
        speed = speed + increment;
        System.out.println(brand + " is now moving at " + speed + " km/h");
    }

    // Method to display car details
    void displayInfo() {
        System.out.println("Car Brand: " + brand);
        System.out.println("Current Speed: " + speed + " km/h");
    }
}

class Main {
    public static void main(String[] args) {
        // Creating an object of Car
        Car car1 = new Car();

        // Initializing car details
        car1.initialize("Toyota", 60);

        // Displaying initial details
        car1.displayInfo();

        // Increasing speed
        car1.increaseSpeed(20);
    }
}

Output:

Car Brand: Toyota
Current Speed: 60 km/h
Toyota is now moving at 80 km/h

Explanation:

  • The Car class has fields for brand and speed.

  • The initialize method sets the initial values.

  • The increaseSpeed method updates the speed and prints a message.

  • The displayInfo method shows the car’s details.

  • In the Main class, we create a car1 object, initialize it, display its details, and increase its speed.

Example Program 3: Managing a Book Class

This program models a Book class with fields for title and price, and methods to update and display the price.

class Book {
    // Fields
    String title;
    double price;

    // Method to set book details
    void setBookDetails(String bookTitle, double bookPrice) {
        title = bookTitle;
        price = bookPrice;
    }

    // Method to apply discount
    void applyDiscount(double discountPercentage) {
        double discount = price * (discountPercentage / 100);
        price = price - discount;
        System.out.println("After " + discountPercentage + "% discount, new price of " + title + " is $" + price);
    }

    // Method to display book details
    void displayBook() {
        System.out.println("Book Title: " + title);
        System.out.println("Price: $" + price);
    }
}

class Main {
    public static void main(String[] args) {
        // Creating an object of Book
        Book book1 = new Book();

        // Setting book details
        book1.setBookDetails("Java Programming", 50.0);

        // Displaying initial details
        book1.displayBook();

        // Applying a discount
        book1.applyDiscount(10);
    }
}

Output:

Book Title: Java Programming
Price: $50.0
After 10.0% discount, new price of Java Programming is $45.0

Explanation:

  • The Book class has fields for title and price.

  • The setBookDetails method initializes the fields.

  • The applyDiscount method reduces the price based on a percentage.

  • The displayBook method prints the book’s details.

  • In the Main class, we create a book1 object, set its details, display them, and apply a discount.

Key Points to Understand

  1. Classes as Blueprints: Classes define the structure (fields) and behavior (methods) of objects. Think of a class as a mold and objects as the items created from that mold.

  2. Objects as Instances: Each object has its own copy of the fields defined in the class. For example, two Student objects can have different names and roll numbers.

  3. Methods for Interaction: Methods allow you to manipulate an object’s data (e.g., setting values, updating fields, or displaying information).

  4. Modularity: OOP encourages organizing code into classes, making it easier to manage and reuse.

Common Questions and Clarifications

Q1: What’s the difference between a class and an object?

  • A class is like a blueprint or template that defines what an object will look like and what it can do. An object is a specific instance created from that class. For example, Student is a class, and student1 is an object of that class.

Q2: Why do we need methods in a class?

  • Methods define the actions or behaviors an object can perform. They allow you to interact with the object’s data in a controlled way, such as setting values, updating data, or displaying information.

Q3: Can a class have multiple objects?

  • Yes! You can create as many objects as needed from a single class. Each object has its own set of field values. For example:

      Student student1 = new Student();
      Student student2 = new Student();
      student1.setDetails("Alice", 101);
      student2.setDetails("Bob", 102);
    

    Here, student1 and student2 are separate objects with different data.

Q4: How do I choose fields and methods for a class?

  • Fields represent the data or state of the object (e.g., a student’s name or a car’s speed). Methods represent the actions you want the object to perform (e.g., displaying details or updating speed). Think about what properties and behaviors the real-world entity you’re modeling should have.

Conclusion

Object-Oriented Programming in Java, even without encapsulation, polymorphism, inheritance, or abstraction, provides a powerful way to structure code using classes and objects. By defining classes with fields and methods, you can model real-world entities and create modular, reusable code. The example programs above—Student, Car, and Book—illustrate how to create classes, instantiate objects, and use methods to manage data.

0
Subscribe to my newsletter

Read articles from Prathamesh Karatkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prathamesh Karatkar
Prathamesh Karatkar