Skip to main content
  1. Resources/
  2. Study Materials/
  3. Information & Communication Technology Engineering/
  4. ICT Semester 4/
  5. Java Programming (4343203)/

7 mins· ·
Milav Dabgar
Author
Milav Dabgar
Experienced lecturer in the electrical and electronic manufacturing industry. Skilled in Embedded Systems, Image Processing, Data Science, MATLAB, Python, STM32. Strong education professional with a Master’s degree in Communication Systems Engineering from L.D. College of Engineering - Ahmedabad.
Java Programming - OOP Fundamentals

Java Programming Language

Chapter 4: Object-Oriented Programming Fundamentals

Building with Objects and Classes


Course: 4343203 - Java Programming

What We'll Cover

  • Procedure-Oriented vs Object-Oriented Programming
  • OOP Concepts (Classes, Objects, Encapsulation, Inheritance, Polymorphism, Abstraction)
  • Creating Classes and Objects
  • Class Attributes and Methods
  • Constructors and Constructor Overloading
  • The 'this' keyword

Object-Oriented Programming Concepts

OOP Concepts

Procedure-Oriented vs Object-Oriented Programming

Procedure-Oriented Programming (POP)

Characteristics:

  • Focus on functions/procedures
  • Data and functions are separate
  • Top-down approach
  • Global data usage
  • Functions operate on data

Examples:

  • C Programming
  • FORTRAN
  • Pascal
  • BASIC

Structure:


// POP Style
int calculate(int a, int b) {
    return a + b;
}
void main() {
    int result = calculate(5, 3);
}
                            

Object-Oriented Programming (OOP)

Characteristics:

  • Focus on objects (data + behavior)
  • Data and functions encapsulated together
  • Bottom-up approach
  • Data hiding and encapsulation
  • Objects interact with each other

Examples:

  • Java
  • C++
  • Python
  • C#

Structure:


// OOP Style
class Calculator {
    int calculate(int a, int b) {
        return a + b;
                            

Comparison: POP vs OOP

AspectProcedure-OrientedObject-Oriented
FocusFunctions/ProceduresObjects (Data + Behavior)
ApproachTop-downBottom-up
Data SecurityLess secure (global data)More secure (encapsulation)
Code ReusabilityLimitedHigh (inheritance)
ModularityFunction-based modulesObject-based modules
Problem SolvingDivide into functionsDivide into objects
Best ForSmall programsLarge, complex systems

Core OOP Concepts

Four Pillars of OOP: Encapsulation, Inheritance, Polymorphism, Abstraction

1. Encapsulation

Definition: Bundling data and methods that operate on data within a single unit

Benefits:

  • Data hiding and protection
  • Controlled access via methods
  • Improved maintainability
  • Reduced dependencies

Example:


class BankAccount {
    private double balance; // Hidden data
    
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
    
    public double getBalance() {
        return balance; // Controlled access
    }
}
                            

2. Inheritance

Definition: Mechanism where a new class inherits properties and behaviors from existing class

Benefits:

  • Code reusability
  • Establishes hierarchy
  • Method overriding
  • Extensibility

Example:


class Animal {
    void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking");
    }
}

Dog dog = new Dog();
dog.eat();  // Inherited method
dog.bark(); // Own method
                            

3. Polymorphism

Definition: Ability of objects to take multiple forms or behave differently

Types:

  • Compile-time: Method overloading
  • Runtime: Method overriding
  • Dynamic method dispatch
  • Interface implementation

Example:


class Animal {
    void makeSound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    void makeSound() {
        System.out.println("Woof!");
    }
}

class Cat extends Animal {
    void makeSound() {
        System.out.println("Meow!");
    }
}

Animal animal = new Dog();
animal.makeSound(); // Output: "Woof!"
                            

4. Abstraction

Definition: Hiding implementation details and showing only essential features

Implementation:

  • Abstract classes
  • Interfaces
  • Access modifiers
  • Method signatures

Example:


interface Shape {
    double area(); // Abstract method
    double perimeter();
}

class Circle implements Shape {
    private double radius;
    
    public double area() {
        return Math.PI * radius * radius;
    }
    
    public double perimeter() {
        return 2 * Math.PI * radius;
    }
}
                            

Classes and Objects

Class: Blueprint/template. Object: Instance of a class

Creating Classes

Class Structure:


public class Car {
    // Fields (attributes)
    private String model;
    private int year;
    private String color;
    
    // Constructor
    public Car(String model, int year) {
        this.model = model;
        this.year = year;
    }
    
    // Methods (behavior)
    public void startEngine() {
        System.out.println("Engine started");
    }
    
    public String getModel() {
        return model;
    }
}
                            

Class Components:

  • Fields: Variables that store object state
  • Methods: Functions that define behavior
  • Constructors: Special methods for object creation
  • Access Modifiers: Control visibility

Naming Conventions:

  • Class names: PascalCase (Car, StudentRecord)
  • Method names: camelCase (startEngine, getModel)
  • Field names: camelCase (model, yearManufactured)

Creating Objects

Object Creation Syntax:


// Syntax
ClassName objectName = new ClassName();

// Examples
Car myCar = new Car("Toyota", 2023);
Car anotherCar = new Car("Honda", 2022);

// Using the objects
myCar.startEngine();
String model = myCar.getModel();
System.out.println("Model: " + model);
                            

Object Creation Process:

  1. Declaration: Car myCar;
  2. Instantiation: new Car()
  3. Assignment: myCar = new Car()
  4. Initialization: Constructor called

Multiple Objects:


Car car1 = new Car("BMW", 2023);
Car car2 = new Car("Audi", 2022);
Car car3 = new Car("Tesla", 2024);

// Each object has its own state
car1.startEngine(); // Independent
car2.startEngine(); // Independent
                            

The 'this' Keyword

'this' refers to the current object instance

Uses of 'this':

  • Distinguish between parameters and fields
  • Call other constructors
  • Return current object
  • Pass current object to methods

Examples:


class Person {
    private String name;
    private int age;
    
    // Constructor with 'this'
    public Person(String name, int age) {
        this.name = name; // Distinguish field from parameter
        this.age = age;
    }
    
    // Method returning 'this'
    public Person setName(String name) {
        this.name = name;
        return this; // Method chaining
    }
    
    // Constructor calling another
    public Person(String name) {
        this(name, 0); // Call parameterized constructor
    }
}
                            

Class Attributes and Methods

Class Attributes (Fields)

Instance Variables:


class Student {
    // Instance variables
    private String name;
    private int rollNumber;
    private double grade;
    
    // Each object has its own copy
    public void setGrade(double grade) {
        this.grade = grade;
    }
}
                            

Class Variables (Static):


class Student {
    // Class variable (shared)
    private static int totalStudents = 0;
    private static String schoolName = "ABC School";
    
    // Instance variables
    private String name;
    
    public Student(String name) {
        this.name = name;
        totalStudents++; // Shared counter
    }
    
    public static int getTotalStudents() {
        return totalStudents;
    }
}
                            

Class Methods

Instance Methods:


class Calculator {
    private double result;
    
    // Instance methods
    public void add(double num) {
        result += num;
    }
    
    public void subtract(double num) {
        result -= num;
    }
    
    public double getResult() {
        return result;
    }
    
    public void reset() {
        result = 0;
    }
}
                            

Static Methods:


class MathUtils {
    // Static methods
    public static double square(double num) {
        return num * num;
    }
    
    public static double max(double a, double b) {
        return (a > b) ? a : b;
    }
    
    public static boolean isEven(int num) {
        return num % 2 == 0;
    }
}

// Usage
double result = MathUtils.square(5); // 25
boolean even = MathUtils.isEven(4);  // true
                            

Method Parameters and Return Values

Method with Parameters:


class Rectangle {
    private double length, width;
    
    // Method with parameters
    public void setDimensions(double length, double width) {
        this.length = length;
        this.width = width;
    }
    
    // Multiple parameters
    public void setDimensions(double length, double width, String unit) {
        this.length = length;
        this.width = width;
        System.out.println("Dimensions set in " + unit);
    }
}
                            

Method with Return Values:


class Rectangle {
    private double length, width;
    
    // Methods returning values
    public double getArea() {
        return length * width;
    }
    
    public double getPerimeter() {
        return 2 * (length + width);
    }
    
    public boolean isSquare() {
        return length == width;
    }
    
    public String getDimensionsInfo() {
        return "Length: " + length + ", Width: " + width;
    }
}
                            

Constructors

Constructors are special methods used to initialize objects

Constructor Types Overview

Java Constructor Types Comparison

Constructor Characteristics

Constructor Rules:

  • Same name as the class
  • No return type (not even void)
  • Called automatically when object is created
  • Can be overloaded
  • Can have access modifiers

Default Constructor:


class Student {
    private String name;
    private int age;
    
    // Default constructor
    public Student() {
        name = "Unknown";
                            

Parameterized Constructor:


class Student {
    private String name;
    private int age;
    
    // Parameterized constructor
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
                            

Constructor Overloading

Constructor Overloading: Multiple constructors with different parameter lists


class Book {
    private String title;
    private String author;
    private int pages;
    private double price;
    
    // Default constructor
    public Book() {
        title = "Unknown";
        author = "Unknown";
        pages = 0;
        price = 0.0;
    }
    
    // Constructor with title only
    public Book(String title) {
        this.title = title;
        author = "Unknown";
        pages = 0;
        price = 0.0;
    }
    
    // Constructor with title and author
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
        pages = 0;
        price = 0.0;
    }
    
    // Full constructor
    public Book(String title, String author, int pages, double price) {
        this.title = title;
        this.author = author;
        this.pages = pages;
        this.price = price;
    }
}
                    

Constructor Chaining

Using 'this()' to call other constructors:


class Employee {
    private String name;
    private int id;
    private double salary;
    
    // Default constructor
    public Employee() {
        this("Unknown", 0, 0.0);
    }
    
    // Constructor with name
    public Employee(String name) {
        this(name, 0, 0.0);
    }
    
    // Constructor with name and id
    public Employee(String name, int id) {
        this(name, id, 0.0);
    }
    
    // Full constructor
    public Employee(String name, int id, double salary) {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }
}
                            

Usage Examples:


// Different ways to create objects
Employee emp1 = new Employee();
Employee emp2 = new Employee("John");
Employee emp3 = new Employee("Jane", 101);
Employee emp4 = new Employee("Bob", 102, 50000);

// All constructors properly initialize the object
System.out.println(emp1.getName()); // "Unknown"
System.out.println(emp2.getName()); // "John"
System.out.println(emp3.getId());   // 101
System.out.println(emp4.getSalary()); // 50000.0
                            

Note: this() must be the first statement in constructor

Chapter Summary

Key Concepts:

  • OOP vs POP paradigms
  • Four pillars of OOP
  • Classes as blueprints
  • Objects as instances
  • Encapsulation and data hiding

Practical Skills:

  • Creating classes and objects
  • Defining attributes and methods
  • Using constructors effectively
  • Constructor overloading
  • Using 'this' keyword properly

Next: Modifiers and String Handling

Thank You!

Questions?


Ready to explore Java modifiers and string operations!