;
Java Basics July 21 ,2025

1. Introduction to Object-Oriented Programming (OOP) in Java

Java is a fully object-oriented programming language, which means it’s centered around creating and using objects. OOP allows developers to model real-world entities like cars, people, or bank accounts into programming structures, making code more modular, scalable, and reusable.

What is Object-Oriented Programming?

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects,” which are instances of classes. These objects can hold data (in the form of fields or attributes) and behaviors (in the form of methods).

This approach helps manage complex software systems by organizing code into logical structures that represent real-world entities.

Why Use OOP?

  • Real-world Modeling: OOP models entities based on how they exist in the real world, making design easier to understand.
  • Reusability: Classes can be reused across programs or extended using inheritance.
  • Maintainability: Code is easier to modify and update without affecting other parts.
  • Security: Through encapsulation and abstraction, you can hide sensitive data and show only necessary parts.
  • Modularity: Divide applications into smaller modules (classes), which can be developed and tested independently.

Comparison: Procedural vs Object-Oriented

FeatureProcedural ProgrammingObject-Oriented Programming
ApproachStep-by-stepBased on objects and classes
Data & BehaviorSeparateCombined in classes
ReusabilityLimitedHigh (via inheritance, classes)
ModularityFunctions/modulesObjects/classes
Example LanguagesC, PascalJava, C++, Python (partially)

Real-Life Analogy

Think of a Car as a real-world object.

  • Attributes (Data): color, model, brand, speed
  • Behaviors (Methods): start(), stop(), accelerate()

In Java, you would create a Car class to represent this, and every real car (object) would be an instance of this class.

Basic Structure of OOP in Java

class Car { // Class declaration
    String color;
    int speed;

    void start() {
        System.out.println("Car started");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car(); // Object creation
        myCar.color = "Red";   // Assign attribute
        myCar.start();         // Call method
    }
}

Key Terms Introduced

  • Class: A blueprint for creating objects.
  • Object: An instance of a class.
  • Method: Defines behavior of the object.
  • Attribute/Field: Variables that store object data.
  • Instantiation: Creating an object from a class using new.

2. The Four Pillars of Object-Oriented Programming in Java

Java is built on four fundamental principles of Object-Oriented Programming (OOP). These are:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction

Each of these concepts contributes to building robust, modular, reusable, and maintainable Java applications.

1. Encapsulation

Definition:
Encapsulation is the process of binding data (variables) and code (methods) together in a class, and restricting direct access to some of the object's components.

It helps in hiding the internal state of the object and only allowing access through public methods (getters and setters).

Benefits:

  • Protects data from unauthorized access
  • Enhances control over data
  • Makes code easier to maintain and modify

Example:

class Student {
    private int age; // private = encapsulated

    public void setAge(int a) {
        if (a > 0) {
            age = a;
        }
    }

    public int getAge() {
        return age;
    }
}

Here, the variable age cannot be accessed directly. It’s accessible only through methods – enforcing encapsulation.

2. Inheritance

Definition:
Inheritance is a mechanism that allows one class (child/subclass) to inherit properties and methods of another class (parent/superclass). It promotes code reuse and supports hierarchical classification.

Benefits:

  • Reduces code duplication
  • Improves code organization
  • Allows extension of existing code

Types:

  • Single Inheritance (Java supports)
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • (Note: Java does not support multiple inheritance with classes, but does with interfaces)

Example:

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

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

public class Test {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();  // Inherited from Animal
        d.bark();
    }
}

3. Polymorphism

Definition:
Polymorphism means “many forms”. It allows an object to behave in multiple ways depending on the context.

Types:

  • Compile-time Polymorphism (Method Overloading)
  • Runtime Polymorphism (Method Overriding)

Benefits:

  • Increases flexibility
  • Enhances code readability and maintenance
  • Enables dynamic behavior

Example 1 – Method Overloading (Compile-time):

class Printer {
    void print(String s) {
        System.out.println(s);
    }

    void print(int i) {
        System.out.println(i);
    }
}

Example 2 – Method Overriding (Runtime):

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

class Dog extends Animal {
    void sound() {
        System.out.println("Bark");
    }
}

4. Abstraction

Definition:
Abstraction is the process of hiding implementation details and showing only essential features of an object.

In Java, abstraction is achieved using:

  • Abstract classes
  • Interfaces

Benefits:

  • Hides complex logic
  • Improves security
  • Enhances simplicity and readability

Example – Abstract Class:

abstract class Shape {
    abstract void draw();
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing Circle");
    }
}

Example – Interface:

interface Vehicle {
    void start();
}

class Bike implements Vehicle {
    public void start() {
        System.out.println("Bike started");
    }
}

 

3. Classes and Objects in Java

In Java, classes and objects are the building blocks of object-oriented programming. A strong understanding of these concepts is essential to write structured, reusable, and real-world Java applications.

What is a Class?

A class is a blueprint or template for creating objects. It defines the properties (variables/fields) and behaviors (methods) that the objects created from it will have.

Think of a class like a recipe—it tells you what ingredients (data) and instructions (methods) are needed, but it's not the actual food (object) itself.

Syntax:

class ClassName {
    // Fields (Variables)
    // Methods (Functions)
}

Example:

class Car {
    // Fields (attributes)
    String color;
    int speed;

    // Method (behavior)
    void start() {
        System.out.println("Car is starting...");
    }
}

What is an Object?

An object is an instance of a class. When a class is instantiated using the new keyword, Java allocates memory for that object and allows access to its fields and methods.

Syntax:

ClassName objName = new ClassName();

Example:

Car myCar = new Car(); // Creating an object
myCar.color = "Red";
myCar.start(); // Accessing method
Classes and Objects in Java - GeeksforGeeks

Creating and Using Objects – Step-by-Step

  1. Define a Class
    Create a class that contains fields and methods.
  2. Create an Object
    Use the new keyword to instantiate the class.
  3. Access Members
    Use the object reference to access variables and methods.

Example in Full:

class Student {
    String name;
    int age;

    void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student(); // Object creation
        s1.name = "Aman";
        s1.age = 20;
        s1.displayInfo(); // Calling method
    }
}

Output:

Name: Aman
Age: 20

Key Concepts to Remember

ConceptDescription
ClassBlueprint or template for objects
ObjectReal-world instance created from a class
FieldVariable declared inside a class
MethodFunction declared inside a class that defines behavior
new KeywordUsed to instantiate (create) an object from a class
Dot Notation .Used to access object fields and methods (objectName.methodName())

Multiple Objects from One Class

You can create as many objects as needed from one class, and each will have its own copy of fields.

Student s1 = new Student();
Student s2 = new Student();
s1.name = "Ananya";
s2.name = "Ravi";

Each object s1 and s2 holds its own data, even though they are created from the same class.

4. Constructor in Java

A constructor in Java is a special method used to initialize objects. Unlike regular methods, constructors are automatically called when an object is created.

What is a Constructor?

A constructor is a block of code that has the same name as the class and no return type, not even void. Its purpose is to assign initial values to an object’s fields when the object is created.

Syntax:

class ClassName {
    ClassName() {
        // constructor body
    }
}

Why Do We Need a Constructor?

  • To assign default or initial values when creating an object.
  • To ensure objects are always in a valid state from the beginning.
  • To simplify initialization logic.

Types of Constructors in Java

Java provides two main types of constructors:

1. Default Constructor

A default constructor is provided by the compiler if no other constructors are written. It takes no arguments and assigns default values (like 0, null, or false).

Example:

class Student {
    String name;
    int age;

    Student() {
        name = "Unknown";
        age = 0;
    }

    void display() {
        System.out.println(name + " - " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student(); // Calls default constructor
        s1.display();
    }
}

Output:

Unknown - 0

2. Parameterized Constructor

This constructor accepts parameters and allows you to initialize fields with specific values.

Example:

class Student {
    String name;
    int age;

    Student(String n, int a) {
        name = n;
        age = a;
    }

    void display() {
        System.out.println(name + " - " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Aman", 20);
        Student s2 = new Student("Riya", 22);
        s1.display();
        s2.display();
    }
}

Output:

Aman - 20  
Riya - 22

3. Constructor Overloading

Just like methods, you can overload constructors—i.e., create multiple constructors with different parameters.

Example:

class Box {
    int length, width;

    // Default Constructor
    Box() {
        length = 0;
        width = 0;
    }

    // Parameterized Constructor
    Box(int l, int w) {
        length = l;
        width = w;
    }

    void show() {
        System.out.println("Length: " + length + ", Width: " + width);
    }
}

 Constructor Chaining in Java

Constructor Chaining is the process of calling one constructor from another constructor in the same class (or from a parent class in case of inheritance).
This helps reuse code, reduce redundancy, and ensures that object initialization is consistent.

Types of Constructor Chaining

There are two types:

  1. Within the Same Class – Using this()
  2. From Subclass to Superclass – Using super()

1. Constructor Chaining Within the Same Class

You can use the this() keyword to call another constructor in the same class.
It must be the first statement in the constructor.

🔹 Example:

class Student {
    String name;
    int age;

    Student() {
        this("Unknown", 0); // Calls parameterized constructor
    }

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void display() {
        System.out.println(name + " - " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();           // Uses default constructor
        Student s2 = new Student("Riya", 22); // Uses parameterized
        s1.display(); // Output: Unknown - 0
        s2.display(); // Output: Riya - 22
    }
}

✅ Benefits:

  • Centralizes initialization logic
  • Reduces code duplication
  • Makes code easier to maintain

2. Constructor Chaining with Inheritance

Using the super() keyword, a constructor can call a constructor from the superclass.
Again, super() must be the first statement in the subclass constructor.

🔹 Example:

class Animal {
    Animal(String type) {
        System.out.println("Type: " + type);
    }
}

class Dog extends Animal {
    Dog() {
        super("Dog"); // Calls parent constructor
        System.out.println("Dog constructor called");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
    }
}

Output:

Type: Dog  
Dog constructor called

📝 Rules of Constructor Chaining

RuleDescription
this()Calls another constructor in the same class
super()Calls a constructor of the parent class
First StatementBoth this() and super() must be the first statement
Only OneYou can only use either this() or super() in a constructor (not both)

✅ Use Cases

  • Setting default values before using parameterized values
  • Reusing parent class logic in child classes
  • Cleaner, maintainable, and DRY (Don't Repeat Yourself) constructor code

 

5.  this Keyword in Java

The this keyword in Java is a reference variable that refers to the current object—i.e., the object whose method or constructor is being executed.

It’s commonly used to resolve naming conflicts, pass current objects as arguments, or call other constructors within the same class.

Why is this Used?

Java allows method parameters and class fields to have the same name. In such cases, this helps distinguish between local variables and instance variables.

1. this to Refer to Instance Variables

When a constructor or method parameter has the same name as a class field, this.variableName refers to the class-level field.

Example:

class Student {
    String name;
    
    Student(String name) {
        this.name = name;  // Refers to the instance variable
    }

    void show() {
        System.out.println("Name: " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Riya");
        s.show(); // Output: Name: Riya
    }
}

Without this.name = name;, Java would assign the parameter to itself, and the instance variable would remain uninitialized.

2. this() to Call Another Constructor

You can use this() to call another constructor in the same class. This promotes constructor chaining, improving code reusability and reducing repetition.

Example:

class Box {
    int length, width;

    Box() {
        this(10, 20); // Calls the parameterized constructor
    }

    Box(int l, int w) {
        length = l;
        width = w;
    }

    void display() {
        System.out.println("Length: " + length + ", Width: " + width);
    }
}

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

3. this as a Method Parameter

You can also use this to pass the current object as an argument to a method or constructor.

Example:

class Student {
    void display(Student s) {
        System.out.println("This is a student object");
    }

    void call() {
        display(this);  // Passing current object
    }
}

4. Returning the Current Object

A method can return this to enable method chaining, which is useful in frameworks like JDBC, Hibernate, or Builder Patterns.

Example:

class Student {
    Student setName(String name) {
        // logic here
        return this;
    }

    Student setAge(int age) {
        // logic here
        return this;
    }
}

 Summary Table

UsagePurpose
this.variableRefers to current object's field
this()Calls another constructor in same class
this as method argumentPasses current object to another method
return this;Returns current object

 

 6. Static vs Instance Members in Java – 

In Java, class members (i.e., variables and methods) can be classified into:

  • Static Members: Belong to the class
  • Instance Members: Belong to individual objects (instances) of the class

Understanding the difference is crucial for writing efficient, maintainable, and organized object-oriented code.

 What Are Instance Members?

Instance members are variables and methods that are associated with an object, not the class.

 Characteristics:

  • Declared without the static keyword.
  • Each object of the class gets its own copy of instance variables.
  • Instance methods can access both instance and static variables.
  • You must create an object to access instance members.

 Example:

class Car {
    String color; // Instance variable

    void showColor() { // Instance method
        System.out.println("Color: " + color);
    }
}

public class Main {
    public static void main(String[] args) {
        Car c1 = new Car();
        c1.color = "Red";
        c1.showColor();  // Output: Color: Red

        Car c2 = new Car();
        c2.color = "Blue";
        c2.showColor();  // Output: Color: Blue
    }
}

 Observation:

  • c1 and c2 are two separate objects with their own color variable.
  • Changing c1.color doesn't affect c2.color.

 Real-Life Analogy:

Think of a Student class. Each student (object) has their own name, age, etc. Those are instance variables.

 What Are Static Members?

Static members belong to the class itself, not to any object.

 Characteristics:

  • Declared using the static keyword.
  • Only one copy exists in memory, shared by all objects.
  • Can be accessed without creating an object.
  • Static methods can access only other static variables/methods directly.
  • Cannot use this keyword in a static context (because this refers to an instance).

 Example:

class MathUtils {
    static int multiply(int a, int b) {
        return a * b;
    }
}

public class Main {
    public static void main(String[] args) {
        int result = MathUtils.multiply(3, 4); // No object needed
        System.out.println(result); // Output: 12
    }
}

Real-Life Analogy:

Imagine a school name — it is common to all students. So instead of giving each student object their own school variable, we make it static.

 Comparison Table: Static vs Instance Members

FeatureStatic MembersInstance Members
Belongs ToClassObject
Keyword UsedstaticNo keyword
Memory AllocationOnly once, when class is loadedEvery time an object is created
Accessed ByClass name or objectOnly via object
Access to this❌ Not allowed✅ Allowed
ExampleStudent.schoolNames1.name, s2.name
Use CaseShared config, constants, countersPersonal data, object-specific properties
Modifiable per object?❌ No, shared across all objects✅ Yes, separate per object

 Key Concept Recap with Code

 Static vs Instance Variable

class Student {
    String name;                   // Instance variable
    static String school = "ABC";  // Static variable

    void display() {
        System.out.println(name + " studies at " + school);
    }
}

 Main Method:

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Riya";

        Student s2 = new Student();
        s2.name = "Aman";

        Student.school = "XYZ"; // Changing static value

        s1.display();  // Output: Riya studies at XYZ
        s2.display();  // Output: Aman studies at XYZ
    }
}

 What Happened?

  • Each student has a unique name (instance member).
  • school is shared — change it once, and all objects reflect that change.

 Important Rules

  1. You can access static variables using:
    • Class name (recommended): ClassName.variable
    • Object (allowed, but not recommended): obj.variable
  2. You cannot access instance variables directly from static methods:

    static void method() {
        System.out.println(name); // ❌ Error
    }
    

    Use object reference instead.

  3. The main method itself is static, so it can't access non-static (instance) members without creating an object.

 Common Interview Questions

Q1: Can static methods use the this keyword?
A: No. this refers to an object. Static methods belong to the class, not any object.

Q2: Is there only one copy of a static variable in memory?
A: Yes, no matter how many objects are created.

Q3: Can you override a static method?
A: No, static methods are resolved at compile time (not runtime), so they cannot be overridden, only hidden.

Q4: When should I use static methods?
A: When functionality is not dependent on object state. Example: utility functions (Math.max(), Integer.parseInt())

 Summary

Use This When...Use Instance When...
You want shared data across all objectsEach object should have its own copy/data
You don’t need to store object-specific dataYou want object-specific behavior/data
You want to call methods without objectMethod logic depends on instance variables
You’re writing utility/helper methodsYou’re modeling real-world entities

 

7. Practice Examples – OOP Basics in Java

These practice examples will help reinforce your understanding of key OOP concepts like classes, objects, constructors, methods, and this keyword, along with the use of static and instance members.

Example 1: Creating a Simple Class and Object

class Dog {
    String name;
    int age;

    void bark() {
        System.out.println(name + " is barking!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d1 = new Dog();
        d1.name = "Tommy";
        d1.age = 4;

        d1.bark(); // Output: Tommy is barking!
    }
}

Explanation:
Here we created a Dog class with instance variables name and age, and a method bark(). We created an object and assigned values before calling the method.

Example 2: Using Constructor and this Keyword

class Book {
    String title;
    double price;

    Book(String title, double price) {
        this.title = title;
        this.price = price;
    }

    void display() {
        System.out.println("Title: " + title + ", Price: ₹" + price);
    }
}

public class Main {
    public static void main(String[] args) {
        Book b1 = new Book("Java Basics", 299.99);
        b1.display(); // Output: Title: Java Basics, Price: ₹299.99
    }
}

Explanation:
The constructor uses this to differentiate between parameter and class field. It initializes the values when the object is created.

Example 3: Static vs Instance Behavior

class Student {
    String name;
    static String schoolName = "ABC Public School";

    void showInfo() {
        System.out.println(name + " studies at " + schoolName);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Riya";

        Student s2 = new Student();
        s2.name = "Aman";

        Student.schoolName = "XYZ International School";

        s1.showInfo(); // Riya studies at XYZ International School
        s2.showInfo(); // Aman studies at XYZ International School
    }
}

Explanation:
Since schoolName is static, any change to it is reflected across all objects.

Example 4: Method Overloading

class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator c = new Calculator();
        System.out.println(c.add(5, 10));        // 15
        System.out.println(c.add(3.5, 6.5));     // 10.0
    }
}

Explanation:
Multiple methods named add with different parameters. This is an example of method overloading, not to be confused with overriding (which involves inheritance).

8. Summary and Use Cases of OOP in Java

 Quick Recap

ConceptDescription
ClassBlueprint for creating objects. Defines properties and behaviors.
ObjectInstance of a class. Has its own state and behavior.
ConstructorSpecial method used to initialize objects. Can be default or parameterized.
this keywordRefers to the current object. Resolves naming conflicts and enables chaining.
Static MembersShared among all instances. Belong to the class, not any specific object.
Instance MembersUnique to each object. Represent the state and behavior of that object.

 Where OOP is Used in Real Life

  1. Banking Systems
    Objects like Account, Customer, Transaction help organize data and logic clearly.
  2. E-Commerce Websites
    Classes like Product, Cart, User, Order, and inheritance for categories.
  3. Mobile Apps (e.g., Android)
    Android development is Java-based and uses OOP principles extensively via Activity, Service, Intent, etc.
  4. Game Development
    Each entity like Player, Enemy, Weapon is modeled as an object.
  5. Educational Platforms
    Course, Student, Instructor, Quiz can all be represented as classes and objects.

 Final Thoughts

OOP provides a structured, modular, and scalable way to build Java applications. It mirrors real-world systems using classes and objects, making code more intuitive, reusable, and easier to maintain.

Mastering these basics is essential before diving into advanced Java topics like inheritance, abstraction, interfaces, exception handling, and file I/O.

 

Next Blog- Access Modifiers & Packages in Java

 

Sanjiv
0

You must logged in to post comments.

Get In Touch

123 Street, New York, USA

+012 345 67890

techiefreak87@gmail.com

© Design & Developed by HW Infotech