Java Tutorial chapters (15)
  1. 01Java Introduction
  2. 02Java Variables & Data Types
  3. 03Java Control Statements
  4. 04Java OOPs Basics
  5. 05Java Inheritance & Polymorphism
  6. 06Java Abstraction & Interfaces
  7. 07Java Strings
  8. 08Java Arrays
  9. 09Java Exception Handling
  10. 10Java Collections Framework
  11. 11Java Multithreading
  12. 12Java 8 Features
  13. 13Java I/O & File Handling
  14. 14Java JDBC
  15. 15Java MCQ

Chapter 04

Java OOPs Basics

6 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Object-Oriented Programming organises code into classes and objects that combine data and behaviour.

This chapter covers the OOP concepts, classes and objects, constructors, the this keyword, the static keyword and method overloading with full programs.

Java is built around classes.

Every framework, interview and project uses these ideas daily.

Modelling students, accounts, products, orders and every real-world entity in business software.

1

OOPs Concepts in Java

Object-Oriented Programming (OOP) is a style of programming that models software as objects containing data (fields) and behaviour (methods). The four main pillars are abstraction, encapsulation, inheritance and polymorphism.

In short: Think of real things like a Car or a Student. Each has data and actions. OOP puts them together in one unit.

Four pillars of OOP

Think about it

OOP makes large programs easier to reuse, extend and test, which is why Java enterprise software is written this way. An online shop has classes Product, Cart, Order and Payment; each class owns its own data and rules.

Object: an instance with state, behaviour and identity.

Class: the blueprint that defines fields and methods.

Abstraction: showing only essential features and hiding the details; done with abstract classes and interfaces.

Encapsulation: wrapping data and methods in one unit and hiding data with private fields and public getters and setters.

Inheritance: a class acquires the fields and methods of another class using extends, giving code reuse and an IS-A relationship.

Polymorphism: one name, many forms; compile-time polymorphism is method overloading and run-time polymorphism is method overriding.

Other terms: coupling (how much classes depend on each other), cohesion (how focused a class is), association, aggregation (HAS-A, parts can live alone) and composition (HAS-A, parts die with the whole).

Java is not 100% object-oriented because it has primitive types and static members.

Key points

  • Object: Runtime instance of a class.
  • Class: Blueprint that defines fields and methods.
  • Abstraction: Hiding implementation, showing only what is needed.
  • Encapsulation: Binding data with methods and hiding it.
  • Inheritance: Acquiring features of a parent class.
  • Polymorphism: Many forms of the same method name.
  • Java is not purely object-oriented because of primitive types.
  • Aim for high cohesion and loose coupling.
  • IS-A means inheritance; HAS-A means association (aggregation or composition).

Example

Code
four pillars in one program:
// File: OopOverview.java
interface Payable {                       // abstraction
    double pay();
}

class Employee implements Payable {
    private String name;                  // encapsulation: private data
    protected double base;

    Employee(String name, double base) { this.name = name; this.base = base; }
    public String getName() { return name; }
    public double pay() { return base; }
}

class Manager extends Employee {          // inheritance (IS-A)
    private double bonus;
    Manager(String name, double base, double bonus) { super(name, base); this.bonus = bonus; }
    @Override
    public double pay() { return base + bonus; }   // polymorphism (overriding)
}

class Company {                            // HAS-A (aggregation)
    Employee[] staff;
    Company(Employee... staff) { this.staff = staff; }
    double payroll() {
        double total = 0;
        for (Employee e : staff) total += e.pay();   // run-time polymorphism
        return total;
    }
}

public class OopOverview {
    public static void main(String[] args) {
        Employee e1 = new Employee("Asha", 30000);
        Employee e2 = new Manager("Ravi", 50000, 15000);
        Company c = new Company(e1, e2);
        System.out.println(e1.getName() + " earns " + e1.pay());
        System.out.println(e2.getName() + " earns " + e2.pay());
        System.out.println("Total payroll: " + c.payroll());   // 95000.0
    }
}
2

Class and Object in Java

A class is a user-defined blueprint that declares fields (state) and methods (behaviour). An object is an instance of a class created with the new keyword; it occupies memory on the heap and has its own copy of the instance fields.

In short: Class is the design of a house. Object is a real house built from that design.

Class blueprint → objects

Think about it

Classes let you model real entities, group related data and keep programs organised. Each row in a student table becomes a Student object in memory.

Syntax

class Student { int id
String name
void show() { ...

} }.

Create an object with Student s = new Student();.

The variable s is a reference stored on the stack and the object lives on the heap.

Several references can point to the same object; assigning s2 = s1 copies the reference, not the object, so a change through s2 is visible through s1.

An object with no reference is eligible for garbage collection.

A reference that points to nothing holds null, and calling a method on it throws NullPointerException.

An anonymous object has no name: new Student().

show(); A class can contain fields, methods, constructors, static and instance initialiser blocks, nested classes and interfaces.

Ways to create objects: new, clone(), deserialisation, reflection (newInstance) and factory methods.

Every class implicitly extends java.

lang.

Object, so toString(), equals() and hashCode() are always available; override toString() to print a readable form.

Key points

  • Instance: An object created from a class.
  • Reference variable: Variable that holds the address of an object.
  • new: Allocates memory and calls the constructor.
  • Anonymous object: Object created without a reference variable.
  • toString(): Method that returns a text form of the object.
  • s2 = s1 copies the reference, not the object.
  • Fields of an object get default values; locals do not.
  • Calling a method on null throws NullPointerException.
  • Override toString() instead of printing fields one by one.

Example

Code
Student class and objects:
class Student {
    int id;
    String name;
    double marks;

    void set(int id, String name, double marks) {
        this.id = id;
        this.name = name;
        this.marks = marks;
    }

    String grade() {
        if (marks >= 75) return "A";
        else if (marks >= 50) return "B";
        return "C";
    }

    @Override
    public String toString() {
        return id + " " + name + " (" + marks + ") grade " + grade();
    }
}

public class ClassObjectDemo {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.set(1, "Asha", 82.5);

        Student s2 = new Student();
        s2.set(2, "Ravi", 61);

        System.out.println(s1);
        System.out.println(s2);

        Student s3 = s1;            // same object, two references
        s3.name = "Asha K";
        System.out.println(s1.name);        // Asha K

        Student empty = new Student();      // default values
        System.out.println(empty.id + " " + empty.name + " " + empty.marks);   // 0 null 0.0

        new Student().set(9, "Temp", 10);   // anonymous object

        Student none = null;
        try {
            none.grade();
        } catch (NullPointerException e) {
            System.out.println("Cannot call a method on null");
        }
    }
}
3

Constructors in Java

A constructor is a special block of code that runs automatically when an object is created with new. It has the same name as the class and no return type. It is used to initialise the fields of the new object.

In short: A constructor sets up the object the moment it is born.

Constructor runs when object is created

Think about it

Constructors guarantee that an object starts in a valid state. new Order(customerId, items) creates an order that is complete from the first line.

Types: default constructor (no parameters; the compiler adds one only if you write none), parameterised constructor and copy constructor (takes another object of the same class; Java has no built-in copy constructor, you write it yourself).

Rules: the name equals the class name, there is no return type, it cannot be abstract, static, final or synchronized, and it can be overloaded.

If you write any constructor, the compiler no longer provides the default one.

Constructor chaining: this(...

) calls another constructor of the same class and super(...

) calls a parent constructor; either must be the first statement.

If no explicit call exists, the compiler inserts super().

A private constructor stops outside code from creating objects (used by Singleton and utility classes).

Initialisation order for new: static blocks (once), instance field initialisers and instance blocks, then the constructor body.

Key points

  • Default constructor: No-argument constructor supplied by the compiler.
  • Parameterised constructor: Constructor that takes values to initialise fields.
  • Copy constructor: Constructor that copies another object of the same class.
  • Constructor chaining: One constructor calling another with this() or super().
  • A constructor has no return type; adding void makes it an ordinary method.
  • this() or super() must be the first statement in a constructor.
  • Writing your own constructor removes the compiler-provided default one.
  • Constructors are not inherited.

Example

Code
constructor types and chaining:
class Book {
    String title;
    String author;
    double price;

    Book() {                                   // default
        this("Untitled", "Unknown", 0);        // chaining
        System.out.println("Default constructor");
    }

    Book(String title) {
        this(title, "Unknown", 0);
    }

    Book(String title, String author, double price) {   // parameterised
        this.title = title;
        this.author = author;
        this.price = price;
        System.out.println("Full constructor for " + title);
    }

    Book(Book other) {                         // copy constructor
        this(other.title, other.author, other.price);
    }

    void show() {
        System.out.println(title + " by " + author + " Rs." + price);
    }
}

public class ConstructorDemo {
    public static void main(String[] args) {
        Book b1 = new Book();
        Book b2 = new Book("Java Basics");
        Book b3 = new Book("Clean Code", "R. Martin", 899);
        Book b4 = new Book(b3);       // copy
        b4.title = "Clean Code (copy)";

        b1.show();
        b2.show();
        b3.show();
        b4.show();
    }
}
4

this Keyword in Java

The this keyword is a reference to the current object, the object whose method or constructor is running. It is used to refer to instance variables, call other constructors, call instance methods and pass the current object.

In short: this means "me, the object that is running this code".

Think about it

this removes ambiguity and enables constructor chaining and fluent APIs. Builders such as new Pizza().cheese().olives().build() return this from each step.

Six common uses: 1) this.

field separates an instance variable from a parameter with the same name (shadowing).

2) this() calls another constructor of the same class.

3) this.

method() calls an instance method of the current object.

4) Pass this as an argument to a method or constructor.

5) Return this to allow method chaining (builder pattern).

6) Use Outer.

this inside an inner class to reach the outer object.

this cannot be used in a static method or static block because no current object exists there.

If a parameter and a field have the same name and you forget this, the assignment affects only the parameter and the field keeps its default value, which is a very common bug.

Key points

  • Shadowing: A local name hides a field with the same name.
  • Method chaining: Calling methods one after another on the returned object.
  • Current object: The instance on which the method was called.
  • this is not available in static contexts.
  • this() must be the first statement in a constructor.
  • Printing this calls toString() of the object.

Example

Code
six uses of this:
class Point {
    int x, y;

    Point(int x, int y) {
        this.x = x;          // field = parameter
        this.y = y;
    }

    Point() {
        this(0, 0);          // call another constructor
    }

    Point moveX(int dx) {
        this.x += dx;
        return this;         // enable chaining
    }

    Point moveY(int dy) {
        this.y += dy;
        return this;
    }

    void register(Registry r) {
        r.add(this);         // pass current object
    }

    @Override
    public String toString() { return "(" + x + ", " + y + ")"; }
}

class Registry {
    void add(Point p) { System.out.println("Registered " + p); }
}

class Broken {
    int value;
    Broken(int value) {
        value = value;       // BUG: assigns parameter to itself, field stays 0
    }
}

public class ThisDemo {
    public static void main(String[] args) {
        Point p = new Point();
        p.moveX(5).moveY(7).moveX(-2);
        System.out.println(p);               // (3, 7)
        p.register(new Registry());
        System.out.println(new Broken(99).value);   // 0 (missing this)
    }
}
5

static Keyword in Java

The static keyword makes a member belong to the class instead of to any object. It can be applied to variables, methods, blocks, nested classes and imports. Static members are loaded once when the class is loaded.

In short: A static member is shared by all objects. You can use it without creating an object.

Special Java keywords that control meaning

Think about it

Static is the right choice for constants, counters, utilities and factory methods that do not depend on a single object. Math.sqrt(), Integer.parseInt(), a global object counter and application configuration.

Static variable: one copy per class, stored with the class data in metaspace, shared by all objects (for example a counter or company name).

Static method: can be called with ClassName.

method(), can access only static members directly and cannot use this or super; main is static for this reason.

Static block: runs once when the class is first loaded, before main and before any object; used for one-time setup.

Static nested class: a nested class that does not need an outer object.

Static import: import static java.

lang.

Math.

*; lets you write sqrt(9).

Static methods cannot be overridden, only hidden.

Instance members can access static members, but static members cannot directly access instance members.

Execution order: static block, then main, then instance block and constructor on each new.

Key points

  • Class variable: Another name for a static variable.
  • Static block: Block that runs once when the class loads.
  • Utility method: Static method that works only on its parameters.
  • Static import: Imports static members so the class name can be skipped.
  • A static method cannot use this, super or instance variables directly.
  • main is static so the JVM can call it without an object.
  • Static blocks run before main when they are in the main class.
  • Static methods are hidden, not overridden.

Example

Code
counter with static members:
class Counter {
    static int created = 0;          // shared by all objects
    static final String COMPANY;     // constant set in static block
    int id;                          // one per object

    static {
        COMPANY = "TechSoft";
        System.out.println("Static block runs once");
    }

    {
        System.out.println("Instance block runs for each object");
    }

    Counter() {
        created++;
        id = created;
    }

    static int total() {             // static method
        return created;              // can use static members
        // return id;                // error: non-static variable id
    }
}

public class StaticDemo {
    static int square(int n) { return n * n; }

    public static void main(String[] args) {
        System.out.println("Before objects: " + Counter.total());
        Counter a = new Counter();
        Counter b = new Counter();
        Counter c = new Counter();
        System.out.println("ids: " + a.id + " " + b.id + " " + c.id);   // 1 2 3
        System.out.println("Total created: " + Counter.total());        // 3
        System.out.println(Counter.COMPANY);
        System.out.println(square(9));                                  // 81
    }
}
6

Method Overloading in Java

Method overloading means defining more than one method with the same name in the same class but with different parameter lists (different number, type or order of parameters). It is compile-time (static) polymorphism.

In short: Same method name, different inputs. The compiler picks the right one by looking at the arguments.

Polymorphism: one call, many forms

Think about it

Overloading gives a clean API: one name for one idea, such as println or Math.max. System.out.println() has overloads for int, double, char, String, boolean and Object.

Overloading is resolved at compile time using the method name and the argument types.

The return type alone cannot distinguish overloaded methods; two methods that differ only in return type give a compile error.

Resolution order for a call: 1) exact match, 2) widening of primitives (int to long), 3) autoboxing, 4) varargs.

For example, calling print(5) when only print(long) and print(Integer) exist chooses print(long) because widening beats boxing.

If two overloads are equally good the call is ambiguous and does not compile: with who(String) and who(Object) the call who(null) picks the more specific String, but with who(String) and who(Integer) the call who(null) is ambiguous.

The main method can be overloaded, but the JVM calls only main(String[] args).

Overloaded methods may have different access modifiers and may throw different exceptions.

Constructors can be overloaded in the same way.

Key points

  • Signature: Method name plus parameter types.
  • Static binding: Method chosen at compile time.
  • Varargs: Variable number of arguments: int... nums
  • Ambiguity: More than one overload fits equally well.
  • Changing only the return type is NOT overloading.
  • Overloading is decided by the reference type at compile time.
  • Widening is preferred over boxing, and boxing over varargs.
  • Static methods can also be overloaded.

Example

Code
overloading and resolution order:
public class OverloadDemo {
    static int add(int a, int b) { return a + b; }
    static int add(int a, int b, int c) { return a + b + c; }
    static double add(double a, double b) { return a + b; }
    static String add(String a, String b) { return a + b; }

    // return type alone is not enough:
    // static double add(int a, int b) { return a + b; }   // compile error

    static void show(long x)    { System.out.println("long " + x); }
    static void show(Integer x) { System.out.println("Integer " + x); }
    static void show(int... x)  { System.out.println("varargs " + x.length); }

    static void who(Object o) { System.out.println("Object"); }
    static void who(String s) { System.out.println("String"); }

    public static void main(String[] args) {
        System.out.println(add(2, 3));          // 5
        System.out.println(add(2, 3, 4));       // 9
        System.out.println(add(2.5, 3.5));      // 6.0
        System.out.println(add("Ja", "va"));    // Java
        System.out.println(add(2, 3.5));        // 5.5  (int widened to double)

        show(5);                                // long 5 (widening wins over boxing)
        show(Integer.valueOf(5));               // Integer 5
        show(1, 2, 3);                          // varargs 3

        who("text");                            // String (most specific)
        who(10);                                // Object (boxing then widening)
        Object o = "text";
        who(o);                                 // Object (reference type decides)
    }
}

Solved examples

Example 01 · Basic

Create a class Rectangle with length and width, a constructor and a method area(). Print the area for 5 x 3.

Given Data:
    Required To Find:

    Area = 15

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Declare fields length and width
    Step 2: Write a constructor using this
    Step 3: Write area() returning length * width
    Step 4: Create an object in main and call area()
    Final Answer: class Rectangle { int length, width; Rectangle(int length, int width) { this.length = length; this.width = width; } int area() { return length * width; } } // new Rectangle(5, 3).area() -> 15

    Approach note: Constructors keep object creation and initialisation in one step.

    Example 02 · Intermediate

    Find the output: static int n = 0; Test() { n++; } main creates three Test objects and prints Test.n.

    Given Data:
      Required To Find:

      Value of n

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: n belongs to the class, so there is one copy
      Step 2: Each constructor call increases the same n
      Step 3: After three objects n is 3
      Final Answer: 3

      Approach note: If n were an instance variable, each object would print 1.

      Example 03 · Intermediate

      Which overload is called: void f(long a), void f(Integer a), void f(int... a) for the call f(10)?

      Given Data:
        Required To Find:

        Chosen method

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: No exact match for int
        Step 2: Widening int to long is tried first
        Step 3: f(long) matches before boxing and varargs
        Final Answer: f(long a)

        Approach note: Order: exact, widening, boxing, varargs.

        Example 04 · Basic

        Create class Box with fields l, w, h and method volume(). Construct Box(2, 3, 4) and print volume.

        Given Data:
          Required To Find:

          Volume 24

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Store dimensions in fields
          Step 2: volume returns l*w*h
          Step 3: 2*3*4 = 24
          Final Answer: class Box { int l,w,h; Box(int l,int w,int h){this.l=l;this.w=w;this.h=h;} int volume(){return l*w*h;} } // new Box(2,3,4).volume() → 24

          Approach note: this.field = param avoids shadowing when names match.

          Real-world applications

          Java

          Using Java OOPs Basics in real projects

          Modelling students, accounts, products, orders and every real-world entity in business software.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: A class takes memory when it is declared.

          Why this is wrong: Only objects created with new use heap memory for fields.

          ✅ Verified Truth: A class is a blueprint; objects are allocated on the heap.

          ⚠️ Exam Tip: Say "class = blueprint, object = instance".

          ❌ Myth: Overloading depends on the return type.

          Why this is wrong: The compiler chooses a method by name and parameters only.

          ✅ Verified Truth: Two methods that differ only in return type cause a compile error.

          ⚠️ Exam Tip: Remember: signature = name + parameter list.

          ❌ Myth: A constructor can have a return type.

          Why this is wrong: With a return type it becomes an ordinary method.

          ✅ Verified Truth: Constructors have the class name and no return type, not even void.

          ⚠️ Exam Tip: Common viva trap.

          ❌ Myth: A static method can use this.

          Why this is wrong: static members belong to the class, not an object.

          ✅ Verified Truth: this is not available in a static method.

          ⚠️ Exam Tip: Static cannot access non-static directly.

          Revision notes

          Object-Oriented Programming organises code into classes and objects that combine data and behaviour. This chapter covers the OOP concepts, classes and objects, constructors, the this keyword, the static keyword and method overloading with full programs.

          High-Yield Quick Revision Points

          1. OOP pillars: abstraction, encapsulation, inheritance, polymorphism.
          2. Class = blueprint; object = instance created with new on the heap; reference holds its address.
          3. Constructor: same name as class, no return type, runs on new; default one is added only if none is written.
          4. this = current object: field access, this(), pass/return this.
          5. static members belong to the class, are loaded once and cannot use this.
          6. Static block runs once at class loading; instance block runs on every new.
          7. Overloading = same name, different parameters, decided at compile time.
          8. Resolution order: exact, widening, boxing, varargs.

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Which is NOT a pillar of OOP?

          Question 2 · MCQ (Interview / semester)

          What is the return type of a constructor?

          Question 3 · MCQ (Interview / semester)

          Where is an object created in memory?

          Question 4 · MCQ (Interview / semester)

          Which statement about static methods is true?

          Question 5 · MCQ (Interview / semester)

          Which is NOT valid overloading?

          Question 6 · MCQ (Interview / semester)

          What must be true about this() in a constructor?