Skip to content

Object Oriented Programming

1. Explain the core concepts of Object-Oriented Programming (OOP) in Java: Encapsulation, Inheritance, and Polymorphism.

Object-Oriented Programming (OOP) is a programming paradigm that organizes a program around objects, which bundle together data (fields) and the methods that operate on that data. This approach promotes clarity, modularity, and reusability.

All OOP languages share three foundational principles: Encapsulation, Polymorphism, and Inheritance.

Encapsulation

Encapsulation is the bundling of data and the methods that act on that data into a single unit, called a class.

Objects are instances of classes and act as self-contained "black boxes" that contain data and associated methods.

Encapsulation also involves restricting direct access to an object's internal state, a concept known as data hiding. It requires all interaction to occur through well-defined interfaces like getter and setter methods.

Access control is achieved through access modifiers such as public, private, and protected.

This separation of internal representation from the external interface enhances modularity, security, and maintainability.

Inheritance

Inheritance is a mechanism where one class (the subclass or child) acquires the properties and behaviors (variables and methods) of another class (the superclass or parent).

Inheritance provides a natural mechanism for expressing hierarchical relationships and primarily supports code reuse.

  • The extends keyword is used for inheriting. For example: class Dog extends Animal { ... }.

  • A subclass inherits all variables and methods defined by the superclass and can add its own unique elements, effectively being a specialized version of its superclass.

  • It promotes code reusability (no need to rewrite the same fields/methods) and creates a logical hierarchy among classes.

  • It models an "is-a" relationship. For example, a Dog is an Animal. The Dog class can inherit common traits like name and age from the Animal class, while also adding its own specific behaviors like bark().

Polymorphism

Polymorphism, meaning "many forms," is the ability of an object to take on many forms. In practice, it allows a single interface (like a method name or a superclass reference) to be used for a general class of actions.

Benefit: It allows to write generic code that works with objects of multiple types for flexibility and dynamic behavior in code.

  • Think of a "draw" command. If you tell a Circle object to draw(), it draws a circle. If you tell a Square object to draw(), it draws a square. The same action draw() results in different behaviors depending on the object.
  1. Method Overloading (Compile-time Polymorphism): A class has multiple methods with the same name but different parameter lists (e.g., add(int, int) and add(double, double)). The correct method to use is chosen at compile-time.

  2. Method Overriding (Runtime Polymorphism): A subclass provides its own specific implementation of a method that is already defined in its superclass. The correct method to call is decided at runtime based on the actual object type. When an overridden method is called through a superclass reference, Java determines which version to execute at run time based on the type of the object being referred to, not the type of the reference variable.


2. Explain each word in the standard Java main method signature: public static void main (String[] args).

The main() method is reserved for the method that begins the execution of a program so it is the entry point for any java application. Every Java program must have a main() method, and all Java code must reside inside a class.

The JVM is designed to find and execute this specific method to start a program.

public static void main(String[] args)

  • public : This is an access modifier. It declares the main method as accessible to everything, including the Java Virtual Machine (JVM) which exists outside of your program's classes. If it weren't public, the JVM wouldn't have permission to call it.

  • static : This is a keyword. It means the method belongs to the class itself, not to a specific instance (object) of the class. The JVM needs to run the main method to start the program, but at that point, no objects have been created yet. static allows the JVM to call main without creating an object of its class first.

  • void : This is the return type. void signifies that the main method does not return any value after it finishes execution. It simply runs the program and then terminates.

  • main : This is the method's name. It's a special, reserved name that the JVM is hard-coded to look for as the starting point of the program. Any other name (e.g., Main, start) will not be recognized by the JVM.

  • (String[] args) : This is the parameter list. It declares a single parameter, which is an array of String objects named args. This array is used to receive any command-line arguments passed when running the program from the terminal.


3. What is a Class? What is an Object? Explain the difference with an example.

A class is a blueprint or template for creating objects. class defines a set of properties (fields) and behaviors (methods) that objects of that type will have. It is a logical construct and doesn't occupy any memory itself.

A well-designed class should define one and only one logical entity, grouping logically connected information. The methods and variables that make up a class are called members of the class, with data members also referred to as instance variables.

An object is a real-world instance of a class. When an object is created, it's a physical entity that exists in memory. Each object gets its own copies of the instance variables defined in the class.

  • Class: HouseBlueprint. is the blueprint that defines the design: number of rooms, number of windows, etc. It's just the plan.

  • Object: An actual House. myHouse and yourHouse are two separate objects built from the same HouseBlueprint. Both have the same design, but they are physically distinct, exist in different locations, and can have different paint colors (i.e., different variable values).

The Dog class is the blueprint. It defines that all dogs will have a name and a breed.

java
// The Class (Blueprint)
class Dog {
    String name;
    String breed;

    void bark() {
        System.out.println("Woof!");
    }
}

buddy and lucy are two separate objects (instances) created from the Dog class.

java
// Creating Objects (Actual Dogs)
Dog buddy = new Dog();
buddy.name = "Buddy";
buddy.breed = "Golden Retriever";

Dog lucy = new Dog();
lucy.name = "Lucy";
lucy.breed = "Poodle";

Here, Dog is the class, while buddy and lucy are distinct objects, each with its own state (name and breed).


4. How do you define a class and create objects from that class in Java? Provide an illustrative example.

Defining and using a class is a two-step process of writing the blueprint (the class), and then creating the actual instances from it (the objects).

Step 1: Define a Class

class is defined using the class keyword. Inside the class, its fields (instance variables) and methods are declared.

java
// General form of a class
class ClassName {
    // Instance variables (data/state)
    type variable1;
    type variable2;
	
    // Methods (behavior)
    returnType methodName(parameters) {
        // method body
    }
}

Step 2: Create Objects

Creating an object is also called instantiation. This is done in two parts:

  1. Declaration: Declare a variable of the class type. This variable will hold a reference to the object. ClassName myObject;

  2. Instantiation: new keyword is used to allocate memory for the object and create an instance. The new operator returns a reference (the memory address) to that new object, which is assigned to the reference variable. myObject = new ClassName();

ClassName myObject = new ClassName();

Object's fields and methods are accessed using the dot operator (.).

java
// DEFINE THE CLASS
class Car {
    String model;
    int year;

    void displayInfo() {
        System.out.println("Model: " + model 
	        + ", Year: " + year);
    }
}

class CarDemo {
    public static void main(String[] args) {
        // CREATE OBJECTS (INSTANCES) FROM THE CLASS
        Car myCar = new Car();
        Car anotherCar = new Car();

        // Set properties for the first Car object
        myCar.model = "Toyota Camry";
        myCar.year = 2024;
        // Set properties for the second Car object
        anotherCar.model = "Honda Civic";
        anotherCar.year = 2023;

        System.out.println("Details of myCar:");
        myCar.displayInfo(); 
        // Output: Model: Toyota Camry, Year: 2024

        System.out.println("\nDetails of anotherCar:");
        anotherCar.displayInfo(); 
        // Output: Model: Honda Civic, Year: 2023
    }
}

Made with ❤️ for students, by a fellow learner.