Comprehensive OOP Notes For Technical Interview Preparation (Using Java)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Comprehensive OOP Notes for Technical

Interview Preparation (Using Java)


Preparing for a technical interview that focuses on Object-Oriented Programming (OOP)
concepts is essential, especially when applying for a software engineering position. This guide
aims to make the whole OOP concept clear by providing detailed explanations and examples in
Java.

Table of Contents
1. Introduction to OOP
2. Classes and Objects
3. Four Pillars of OOP
○ Encapsulation
○ Abstraction
○ Inheritance
○ Polymorphism
4. Access Modifiers in Java
5. Constructors and Garbage Collection
6. Static Members
7. Method Overloading and Overriding
8. Interfaces and Abstract Classes
9. Association, Aggregation, and Composition
10. Design Patterns
11. SOLID Principles
12. Advanced Topics
13. Interview Tips

1. Introduction to OOP
Object-Oriented Programming (OOP) is a programming paradigm centered around objects
rather than actions. It allows developers to create modular, reusable code by modeling
real-world entities as software objects that have data fields and associated procedures known
as methods.

Key Benefits of OOP:


● Modularity: The source code for an object can be written and maintained independently.
● Reusability: Objects can be reused across programs.
● Pluggability and Debugging Ease: If a particular object turns out to be problematic,
you can simply remove it and plug in a different object.

2. Classes and Objects


● Class: A blueprint or template from which objects are created. It defines the properties
(attributes) and behaviors (methods) common to all objects of a certain kind.
● Object: An instance of a class. It is a real-world entity that has state and behavior.

Example in Java:
public class Car {
// Attributes (state)
private String brand;
private String color;

// Constructor
public Car(String brand, String color) {
this.brand = brand;
this.color = color;
}

// Methods (behavior)
public void drive() {
"."); System.out.println("Driving the " + color + " " + brand +
}

// Getters and Setters


public String getBrand() {
return brand;
}

public String getColor() {


return color;
}
}

// Using the class


public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", "Red");
myCar.drive(); // Outputs: Driving the Red Toyota.
}
}

3. Four Pillars of OOP


a. Encapsulation

Definition: Encapsulation is the mechanism of wrapping the data (variables) and the code
acting on the data (methods) together as a single unit, and restricting direct access to some of
an object's components.

Key Points:

● Protects the internal state of an object from unintended external modification.


● Achieved using access modifiers (private, protected, public).

Example in Java:
public class BankAccount {
private double balance = 0.0;

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
}
}

public double getBalance() {


return balance;
}
}

// Usage
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000.0);

// account.balance = 5000.0; // Error: balance has private


access

System.out.println("Balance: " + account.getBalance()); //


Outputs: Balance: 1000.0

}
}
b. Abstraction

Definition: Abstraction is the concept of hiding the complex reality while exposing only the
necessary parts. It focuses on the essential qualities rather than the specific characteristics of
one particular example.

Key Points:

● Achieved using abstract classes and interfaces.


● Simplifies code complexity by providing a simplified model.

Example in Java using an Abstract Class:


abstract class Shape {
abstract double area();
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
double area() {
return Math.PI * radius * radius;
}
}

// Usage

public class Main {

public static void main(String[] args) {

Shape shape = new Circle(5);

System.out.println("Area: " + shape.area()); // Outputs: Area:


78.53981633974483

}
c. Inheritance

Definition: Inheritance allows a new class to inherit properties and methods from an existing
class. The new class is called the subclass (child class), and the existing class is called the
superclass (parent class).

Key Points:

● Promotes code reusability.


● Supports hierarchical classifications.

Example in Java:
class Animal {
public void eat() {
System.out.println("Eating...");
}
}

class Dog extends Animal {


public void bark() {
System.out.println("Barking...");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Dog's own method
}
}
d. Polymorphism

Definition: Polymorphism allows objects to be treated as instances of their parent class rather
than their actual class. The same method can perform different functions based on the object
that it is acting upon.

Types of Polymorphism:

1. Compile-Time Polymorphism (Method Overloading)


2. Run-Time Polymorphism (Method Overriding)

Compile-Time Polymorphism (Method Overloading)

● Achieved by defining multiple methods with the same name but different parameter lists
within the same class.
● The compiler determines which method to call based on the method signature.

Example in Java:
class Calculator {
// Method Overloading
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}

public int add(int a, int b, int c) {


return a + b + c;
}
}

// Usage
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 3)); // Outputs: 8
System.out.println(calc.add(2.5, 3.5)); // Outputs: 6.0
System.out.println(calc.add(1, 2, 3)); // Outputs: 6
}
}

Run-Time Polymorphism (Method Overriding)

● Achieved when a subclass overrides a method from its superclass.


● The method to be executed is determined at runtime based on the object's actual type.

Example in Java:
class Shape {
public void draw() {
System.out.println("Drawing a shape.");
}
}

class Rectangle extends Shape {


@Override
public void draw() {
System.out.println("Drawing a rectangle.");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Shape shape1 = new Shape();
Shape shape2 = new Rectangle();

shape1.draw(); // Outputs: Drawing a shape.


shape2.draw(); // Outputs: Drawing a rectangle.
}
}
4. Access Modifiers in Java
Access modifiers define the scope of a class, constructor, variable, method, or data member.

● public: Accessible from any other class.


● protected: Accessible within the same package and subclasses.
● default (no modifier): Accessible within the same package.
● private: Accessible only within the declared class.

Example in Java:
public class AccessModifiersDemo {
public String publicVar = "Public";
protected String protectedVar = "Protected";
String defaultVar = "Default";
private String privateVar = "Private";

public void testAccess() {


// All variables are accessible here
System.out.println(publicVar);
System.out.println(protectedVar);
System.out.println(defaultVar);
System.out.println(privateVar);
}
}

class SubClass extends AccessModifiersDemo {

public void testAccess() {

System.out.println(publicVar); // Accessible

System.out.println(protectedVar); // Accessible

System.out.println(defaultVar); // Accessible within the


same package

// System.out.println(privateVar); // Error: privateVar has


private access

class OtherClass {
public void testAccess() {

AccessModifiersDemo obj = new AccessModifiersDemo();

System.out.println(obj.publicVar); // Accessible

System.out.println(obj.protectedVar); // Error: protectedVar


has protected access

System.out.println(obj.defaultVar); // Accessible within the


same package

// System.out.println(obj.privateVar);// Error: privateVar has


private access

}
5. Constructors and Garbage Collection
Constructors

● A constructor is a block of code similar to a method that's called when an instance of an


object is created.
● Used to initialize objects.
● Constructor name must match the class name.
● Does not have a return type.

Example in Java:
public class Person {
private String name;

// Constructor
public Person(String name) {
this.name = name;
}

// Method
public void greet() {
System.out.println("Hello, my name is " + name + ".");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Person person = new Person("Alice");
person.greet(); // Outputs: Hello, my name is Alice.
}
}

Garbage Collection

● Java handles memory management automatically through garbage collection.


● When objects are no longer referenced, they become eligible for garbage collection.
● The finalize() method can be overridden to perform cleanup before an object is
collected, but it's not recommended for use in modern Java applications.
6. Static Members
● Static Variables: Class variables shared among all instances.
● Static Methods: Can be called without creating an instance of the class.
● Static Block: Used to initialize static variables.

Example in Java:
public class MathHelper {
public static final double PI = 3.14159;

public static double square(double number) {


return number * number;
}
}

// Usage

public class Main {

public static void main(String[] args) {

System.out.println("PI: " + MathHelper.PI); //


Outputs: PI: 3.14159

System.out.println("Square: " + MathHelper.square(5)); //


Outputs: Square: 25.0

}
7. Method Overloading and Overriding
Method Overloading

● Multiple methods in the same class with the same name but different parameters.
● Compile-time polymorphism.

Example in Java:
public class Printer {
public void print(String text) {
System.out.println(text);
}

public void print(int number) {


System.out.println(number);
}

public void print(String text, int number) {


System.out.println(text + " " + number);
}
}

// Usage
public class Main {
public static void main(String[] args) {
Printer printer = new Printer();
printer.print("Hello"); // Outputs: Hello
printer.print(100); // Outputs: 100
printer.print("Number", 200); // Outputs: Number 200
}
}
Method Overriding

● Subclass provides a specific implementation of a method declared in its superclass.


● Run-time polymorphism.

Example in Java:
class Vehicle {
public void start() {
System.out.println("Vehicle is starting.");
}
}

class Car extends Vehicle {


@Override
public void start() {
System.out.println("Car is starting.");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Vehicle myVehicle = new Car();
myVehicle.start(); // Outputs: Car is starting.
}
}
8. Interfaces and Abstract Classes
Interfaces

● Defines a contract with abstract methods (methods without a body).


● A class that implements an interface must provide implementations for all its methods.
● Supports multiple inheritance of type.

Example in Java:
public interface Drawable {
void draw();
}

class Circle implements Drawable {


@Override
public void draw() {
System.out.println("Drawing a circle.");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Drawable drawable = new Circle();
drawable.draw(); // Outputs: Drawing a circle.
}
}
Abstract Classes

● Cannot be instantiated.
● May contain abstract methods and concrete methods.
● A subclass must override all abstract methods unless it is also abstract.

Example in Java:
public abstract class Animal {
public abstract void makeSound();

public void sleep() {


System.out.println("Sleeping...");
}
}

class Cat extends Animal {


@Override
public void makeSound() {
System.out.println("Meow!");
}
}

// Usage
public class Main {
public static void main(String[] args) {
Animal animal = new Cat();
animal.makeSound(); // Outputs: Meow!
animal.sleep(); // Outputs: Sleeping...
}
}
9. Association, Aggregation, and Composition
Association

● A relationship between two classes where there is no ownership.


● Both classes can exist independently.

Example in Java:
class Teacher {
private String name;
// Constructor, getters, setters
}

class Student {
private String name;
// Constructor, getters, setters
}

class Course {
private Teacher teacher;
private List<Student> students;

public Course(Teacher teacher) {


this.teacher = teacher;
this.students = new ArrayList<>();
}

public void addStudent(Student student) {


students.add(student);
}
}
Aggregation

● A specialized form of association.


● Represents a "has-a" relationship.
● The child can exist independently of the parent.

Example in Java:
class Department {
private String name;
private List<Teacher> teachers;

public Department(String name) {


this.name = name;
this.teachers = new ArrayList<>();
}

public void addTeacher(Teacher teacher) {


teachers.add(teacher);
}
}

// Teachers can exist without the Department


Composition

● A strong form of aggregation.


● Represents a "part-of" relationship.
● The child cannot exist without the parent.

Example in Java:
class Engine {
// Engine details
}

class Car {
private Engine engine;

public Car() {
created engine = new Engine(); // Engine is created when Car is
}
}

// Engine cannot exist without Car


10. Design Patterns
Design patterns are standard solutions to common problems in software design.

Singleton Pattern

● Ensures that a class has only one instance and provides a global point of access to it.

Example in Java:
public class Singleton {
private static Singleton instance;

private Singleton() {
// Private constructor prevents instantiation
}

public static Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

// Usage
public class Main {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
}
}
Factory Pattern

● Defines an interface for creating an object but lets subclasses alter the type of objects
that will be created.

Example in Java:

interface Shape {
void draw();
}

class Circle implements Shape {


@Override
public void draw() {
System.out.println("Drawing Circle.");
}
}

class Rectangle implements Shape {


@Override
public void draw() {
System.out.println("Drawing Rectangle.");
}
}

class ShapeFactory {
public static Shape getShape(String shapeType) {
if ("CIRCLE".equalsIgnoreCase(shapeType)) {
return new Circle();
} else if ("RECTANGLE".equalsIgnoreCase(shapeType)) {
return new Rectangle();
}
return null;
}
}

// Usage
public class Main {
public static void main(String[] args) {
Shape shape1 = ShapeFactory.getShape("CIRCLE");
shape1.draw(); // Outputs: Drawing Circle.
Shape shape2 = ShapeFactory.getShape("RECTANGLE");
shape2.draw(); // Outputs: Drawing Rectangle.
}
}

11. SOLID Principles


SOLID is an acronym for five design principles that help developers build robust and
maintainable systems.

S - Single Responsibility Principle

● A class should have only one reason to change.

O - Open/Closed Principle

● Classes should be open for extension but closed for modification.

L - Liskov Substitution Principle

● Objects of a superclass should be replaceable with objects of a subclass without


affecting the correctness of the program.

I - Interface Segregation Principle

● No client should be forced to depend on methods it does not use.

D - Dependency Inversion Principle

● Depend upon abstractions, not upon concrete implementations.

Example Applying SOLID Principles:

Suppose we have a Worker interface that includes methods not all workers need:
interface Worker {
void work();
void eat();
}
This violates the Interface Segregation Principle because not all workers may need to eat()
(e.g., robots). A better approach:
interface Workable {
void work();
}

interface Eatable {
void eat();
}

class HumanWorker implements Workable, Eatable {


@Override
public void work() {
// Human working
}

@Override
public void eat() {
// Human eating
}
}

class RobotWorker implements Workable {


@Override
public void work() {
// Robot working
}
}
12. Advanced Topics
Generics

● Enable types (classes and interfaces) to be parameters when defining classes,


interfaces, and methods.

Example in Java:
public class Box<T> {
private T item;

public void add(T item) {


this.item = item;
}

public T get() {
return item;
}
}

// Usage
public class Main {
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.add("Hello");
System.out.println(stringBox.get()); // Outputs: Hello

Box<Integer> intBox = new Box<>();


intBox.add(123);
System.out.println(intBox.get()); // Outputs: 123
}
}
Exception Handling

● Mechanism to handle runtime errors, allowing normal program flow to continue.

Example in Java:

try {

int result = 10 / 0;

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero.");

} finally {

System.out.println("Finally block executed.");

Annotations

● Provide metadata about the program that is not part of the program itself.

Example in Java:

java

Copy code

public class MyClass {

@Override

public String toString() {

return "MyClass";

}
13. Interview Tips
● Understand Concepts Deeply: Go beyond memorizing definitions; understand how to
apply OOP concepts in real-world scenarios.
● Practice Coding: Write code by hand or on a whiteboard to simulate the interview
environment.
● Explain Your Thought Process: Be prepared to discuss why you chose a particular
solution.
● Review Java Syntax and Libraries: Be familiar with Java's core libraries and syntax.
● Study Common Design Patterns: Understand when and how to use patterns like
Singleton, Factory, Observer, etc.
● Prepare Examples: Have examples ready for each OOP concept.
● Ask Clarifying Questions: If a problem is not clear during the interview, ask for more
information.
● Stay Calm and Confident: Confidence shows that you are comfortable with the
material.

Final Thoughts:

Understanding OOP concepts thoroughly is essential for a software engineer. Using Java for
your examples provides concrete experience with a language widely used in the industry. By
mastering these concepts and practicing their application, you'll be well-prepared for your
technical interview.

Good luck with your technical interview at Welldev!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy