CS Engineering Gyan

Object-Oriented Programming in Java

As programs grow in size and complexity, organizing code around individual functions and variables alone becomes difficult to manage. Object-Oriented Programming, commonly known as OOP, offers a different approach by organizing software around real-world entities called objects, each with their own data and behavior.

Java was designed from the ground up as an object-oriented language, meaning almost everything in Java revolves around classes and objects. This approach makes programs easier to design, extend, and maintain, especially as projects grow beyond simple, single-file applications.

In this tutorial, you will learn the core pillars of Object-Oriented Programming in Java, including classes, objects, constructors, inheritance, polymorphism, abstraction, and encapsulation, along with practical examples for each concept.


What is Object-Oriented Programming?

Object-Oriented Programming is a programming approach that models software design around objects, which represent real-world entities containing both data and the actions that can be performed on that data. Instead of writing isolated functions, OOP groups related data and behavior together inside classes.

Example

class Channel {

    String name = "CS Engineering Gyan";

    void displayInfo() {

        System.out.println("Welcome to " + name);

    }

}

public class OopsIntroExample {

    public static void main(String[] args) {

        Channel channel = new Channel();

        channel.displayInfo();

    }

}

Output

Welcome to CS Engineering Gyan

In this example, Channel is a class that groups together a piece of data (name) and a related behavior (displayInfo), reflecting how OOP organizes real-world concepts into structured code.


Classes and Objects

A class acts as a blueprint that defines the properties and behaviors an object will have, while an object is an actual instance created from that blueprint. You can create many different objects from a single class, each holding its own independent data.

Example

class Video {

    String title;

    int views;

}

public class ClassObjectExample {

    public static void main(String[] args) {

        Video video1 = new Video();

        video1.title = "Java OOPs Concepts";

        video1.views = 3200;

        Video video2 = new Video();

        video2.title = "Java Methods Explained";

        video2.views = 4500;

        System.out.println("CS Engineering Gyan - " + video1.title + " (" + video1.views + " views)");

        System.out.println("CS Engineering Gyan - " + video2.title + " (" + video2.views + " views)");

    }

}

Output

CS Engineering Gyan - Java OOPs Concepts (3200 views)

CS Engineering Gyan - Java Methods Explained (4500 views)

Here, video1 and video2 are two separate objects created from the same Video class, each maintaining its own independent title and view count.


Constructors in Java

A constructor is a special method automatically called when an object is created, typically used to initialize the object's data. Constructors share the same name as the class and do not have a return type, not even void.

Example

class Playlist {

    String name;

    int videoCount;

    Playlist(String name, int videoCount) {

        this.name = name;

        this.videoCount = videoCount;

    }

    void displayPlaylist() {

        System.out.println("CS Engineering Gyan playlist: " + name + " (" + videoCount + " videos)");

    }

}

public class ConstructorExample {

    public static void main(String[] args) {

        Playlist javaPlaylist = new Playlist("Java Basics", 25);

        javaPlaylist.displayPlaylist();

    }

}

Output

CS Engineering Gyan playlist: Java Basics (25 videos)

The keyword this is used inside the constructor to distinguish between the class's instance variables and the parameters passed in, since they share the same name in this example.


Encapsulation

Encapsulation is the practice of keeping a class's internal data private and controlling access to it through public methods, commonly known as getters and setters. This protects the data from being changed in unexpected or invalid ways from outside the class.

Example

class Subscriber {

    private int subscriberCount;

    void setSubscriberCount(int count) {

        if (count >= 0) {

            subscriberCount = count;

        }

    }

    int getSubscriberCount() {

        return subscriberCount;

    }

}

public class EncapsulationExample {

    public static void main(String[] args) {

        Subscriber subscriber = new Subscriber();

        subscriber.setSubscriberCount(105000);

        System.out.println("CS Engineering Gyan subscribers: " + subscriber.getSubscriberCount());

    }

}

Output

CS Engineering Gyan subscribers: 105000

Since subscriberCount is marked as private, it cannot be accessed directly from outside the class. Instead, the setter method allows validation logic, such as preventing negative values, before the data is actually updated.


Inheritance

Inheritance allows one class to acquire the properties and behaviors of another class, promoting code reuse and establishing a natural relationship between related classes. The class being inherited from is called the parent or superclass, while the class that inherits is called the child or subclass.

Syntax

class Subclass extends Superclass {

    // additional properties and methods

}

Example

class Channel {

    String name = "CS Engineering Gyan";

    void showChannelName() {

        System.out.println("Channel: " + name);

    }

}

class TechChannel extends Channel {

    String category = "Programming Tutorials";

    void showCategory() {

        System.out.println("Category: " + category);

    }

}

public class InheritanceExample {

    public static void main(String[] args) {

        TechChannel techChannel = new TechChannel();

        techChannel.showChannelName();

        techChannel.showCategory();

    }

}

Output

Channel: CS Engineering Gyan

Category: Programming Tutorials

Notice that TechChannel can directly use the showChannelName method defined in Channel, without needing to rewrite it, since it inherits that behavior automatically through the extends keyword.


Types of Inheritance in Java

Type Description
Single Inheritance One subclass inherits from a single superclass.
Multilevel Inheritance A class inherits from a subclass, forming a chain of inheritance.
Hierarchical Inheritance Multiple subclasses inherit from the same single superclass.

It is worth noting that Java does not support multiple inheritance through classes, meaning a class cannot directly extend more than one class at the same time. This restriction is designed to avoid ambiguity when two parent classes might define conflicting behavior.


Polymorphism

Polymorphism means "many forms" and refers to the ability of a single method name to behave differently depending on the context in which it is used. Java achieves polymorphism mainly through method overloading and method overriding.

Method Overriding Example

class Channel {

    void uploadSchedule() {

        System.out.println("Default upload schedule: Weekly");

    }

}

class CSEngineeringGyan extends Channel {

    @Override

    void uploadSchedule() {

        System.out.println("CS Engineering Gyan upload schedule: Twice a week");

    }

}

public class PolymorphismExample {

    public static void main(String[] args) {

        Channel channel = new CSEngineeringGyan();

        channel.uploadSchedule();

    }

}

Output

CS Engineering Gyan upload schedule: Twice a week

In this example, the subclass provides its own version of the uploadSchedule method, overriding the one defined in the parent class. Even though the reference type is Channel, Java calls the overridden version based on the actual object type at runtime.


Abstraction

Abstraction focuses on exposing only the essential features of an object while hiding the internal implementation details. In Java, abstraction is commonly achieved using abstract classes and interfaces, both of which define what a class should do without necessarily specifying exactly how.

Example

abstract class ContentCreator {

    abstract void createContent();

}

class CSEngineeringGyanCreator extends ContentCreator {

    void createContent() {

        System.out.println("CS Engineering Gyan creates programming tutorial videos.");

    }

}

public class AbstractionExample {

    public static void main(String[] args) {

        ContentCreator creator = new CSEngineeringGyanCreator();

        creator.createContent();

    }

}

Output

CS Engineering Gyan creates programming tutorial videos.

Here, the abstract class ContentCreator defines that every content creator must implement a createContent method, without dictating exactly how that content should be created. Each subclass is free to implement this method in its own specific way.


Four Pillars of OOP Summarized

Pillar Purpose
Encapsulation Protects data by restricting direct access and exposing controlled methods instead.
Inheritance Allows a class to reuse properties and behaviors from another class.
Polymorphism Allows the same method name to behave differently in different contexts.
Abstraction Hides implementation details while exposing only essential functionality.

Together, these four pillars form the foundation of object-oriented design, guiding how classes and objects should be structured to create flexible, maintainable, and reusable software.


The this Keyword

The this keyword refers to the current object within a class and is commonly used to distinguish instance variables from parameters that share the same name, or to call another constructor within the same class.

Example

class Video {

    String title;

    Video(String title) {

        this.title = title;

    }

    void display() {

        System.out.println("CS Engineering Gyan video: " + this.title);

    }

}

public class ThisKeywordExample {

    public static void main(String[] args) {

        Video video = new Video("Understanding this Keyword");

        video.display();

    }

}

Output

CS Engineering Gyan video: Understanding this Keyword

Why Object-Oriented Programming Matters


Best Practices for Object-Oriented Design


Common Mistakes Beginners Make

Mistake Correct Practice
Making all class variables public by default. Use private access modifiers and expose data through getters and setters when needed.
Confusing method overloading with method overriding. Remember overloading changes parameters within the same class, while overriding redefines a method in a subclass.
Using inheritance where no logical relationship exists between classes. Only use inheritance when a subclass truly represents a specific type of the parent class.
Forgetting to initialize object data through constructors. Use constructors to properly initialize an object's data at the time of creation.

Frequently Asked Interview Questions

  1. What is Object-Oriented Programming?
    It is a programming approach that organizes software around objects containing both data and related behavior.
  2. What is the difference between a class and an object?
    A class is a blueprint that defines properties and behavior, while an object is an actual instance created from that class.
  3. What is the purpose of a constructor in Java?
    A constructor initializes an object's data automatically when the object is created.
  4. What is encapsulation, and why is it important?
    Encapsulation restricts direct access to a class's data, protecting it from unintended or invalid changes.
  5. What is the difference between method overloading and method overriding?
    Overloading defines multiple methods with the same name but different parameters in the same class, while overriding redefines a parent class method inside a subclass.
  6. Does Java support multiple inheritance through classes?
    No, Java does not allow a class to directly extend more than one class at the same time.
  7. What is the purpose of an abstract class?
    An abstract class defines methods that must be implemented by subclasses, without specifying how those methods should work internally.
  8. What does the this keyword refer to in Java?
    It refers to the current object within a class, often used to resolve naming conflicts between instance variables and parameters.

Summary

Object-Oriented Programming forms the backbone of Java, shaping how classes and objects are designed, connected, and reused throughout an application. By understanding classes, objects, and constructors, you gain the ability to model real-world entities directly within your code.

The four core pillars, encapsulation, inheritance, polymorphism, and abstraction, work together to make Java programs more secure, reusable, flexible, and easier to understand. Mastering these concepts is essential for writing well-structured Java applications that can grow and adapt over time without becoming unmanageable.

With a solid foundation in Object-Oriented Programming, you are now ready to explore exception handling, which allows Java programs to detect and respond to unexpected errors gracefully during execution.


← Previous: Methods in Java Next: Exception Handling →

Home Visit Our YouTube Channel