Java OOP Concepts
🧠 Objective:
At the end, learners will be able to:
Understand and apply Object-Oriented Programming (OOP) concepts.
Use Java classes, objects, constructors, inheritance, polymorphism, encapsulation, and
abstraction effectively.
Connect Java OOP concepts to Selenium framework needs (e.g., WebDriver as interface).
1. Classes and Objects
What is a Class?
A class is a blueprint for objects. It contains fields (attributes) and methods (behavior).
public class Car {
String brand;
int speed;
void drive() {
System.out.println("Driving " + brand + " at " + speed + " km/h");
}
}
What is an Object?
An object is an instance of a class.
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Object created
myCar.brand = "Toyota";
myCar.speed = 120;
myCar.drive();
}
}
🎓 Real-Time Use Case: Object = “Google Chrome browser instance”, Class = “WebDriver”
2. Constructors
What is a Constructor?
A constructor is a special method used to initialize objects. It has the same name as the class and
no return type.
public class Employee {
String name;
int id;
1 | 13
Java OOP Concepts
// Constructor
Employee(String name, int id) {
this.name = name;
this.id = id;
}
void show() {
System.out.println(name + " - " + id);
}
}
Employee emp = new Employee("John", 101);
emp.show();
🔁 Constructor Overloading is possible by using different parameter lists.
3. Inheritance (IS-A Relationship)
Concept:
Inheritance allows one class to acquire the fields and methods of another class.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
Dog d = new Dog();
d.sound(); // from parent
d.bark(); // from child
super keyword:
Used to access parent class methods or constructors.
class Animal {
Animal() {
System.out.println("Animal constructor");
}
}
class Dog extends Animal {
Dog() {
super(); // Calls Animal's constructor
System.out.println("Dog constructor");
}
2 | 13
Java OOP Concepts
🎯 Use in Selenium: RemoteWebDriver extends WebDriver (Inheritance)
4. Polymorphism
Method Overloading (Compile-time Polymorphism):
Same method name with different parameters in the same class.
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Method Overriding (Runtime Polymorphism):
Subclass provides specific implementation of a method already defined in its superclass.
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}
🛠️ChromeDriver,
Real Use Case: Selenium's findElement() is overridden in different drivers like
FirefoxDriver, etc.
5. Encapsulation
Definition:
Encapsulation is the process of wrapping variables and methods together in a single unit (class) and
restricting direct access to fields.
class Student {
private String name; // Private field
public void setName(String name) {
3 | 13
Java OOP Concepts
this.name = name;
}
public String getName() {
return name;
}
}
🎓 Why: Improves code security, flexibility, and control over data
6. Abstraction
Abstract Class:
Cannot be instantiated. May have both abstract and non-abstract methods.
abstract class Shape {
abstract void draw();
void color() {
System.out.println("Coloring...");
}
}
Interface:
Fully abstract (Java 7), may have default/static methods (Java 8+)
interface WebDriver {
void get(String url);
void close();
}
class ChromeDriver implements WebDriver {
public void get(String url) {
System.out.println("Opening " + url + " in Chrome");
}
public void close() {
System.out.println("Closing Chrome");
}
}
💡reference
Selenium Insight: WebDriver driver = new ChromeDriver(); (Interface
→ implementation object)
🧪 Hands-On Practice Exercises
🔁 Practice 1:
Create a class BankAccount with deposit and withdraw methods. Use constructor, encapsulation,
and inheritance.
4 | 13
Java OOP Concepts
🔁 Practice 2:
Create an abstract class Device with abstract method start(). Implement it in class Mobile.
🔁 Practice 3:
Create a class Calculator with overloaded add() methods.
------------------------------------------------------------------
Example 1: Healthcare Domain – Patient Management System
Problem Statement:
In a hospital, patients are categorized as InPatients and OutPatients. We need to store patient
details, calculate total billing (based on stay or consultation), and ensure secure access to sensitive
data using OOP principles.
Applied Concepts:
Class & Object: Patient details
Constructor: Initialize data
Inheritance: InPatient & OutPatient inherit from Patient
Method Overriding: Custom billing
Encapsulation: Private fields with getters/setters
Abstraction: Base class defines the contract
Code:
abstract class Patient {
private String name;
private int age;
public Patient(String name, int age) {
this.name = name;
this.age = age;
}
// Getters (Encapsulation)
public String getName() { return name; }
public int getAge() { return age; }
// Abstract method (Abstraction)
abstract double calculateBill();
}
// InPatient Class (Inheritance + Overriding)
class InPatient extends Patient {
5 | 13
Java OOP Concepts
private int daysAdmitted;
private double dailyRate;
public InPatient(String name, int age, int daysAdmitted, double dailyRate) {
super(name, age);
this.daysAdmitted = daysAdmitted;
this.dailyRate = dailyRate;
}
@Override
double calculateBill() {
return daysAdmitted * dailyRate;
}
}
// OutPatient Class
class OutPatient extends Patient {
private double consultationFee;
public OutPatient(String name, int age, double consultationFee) {
super(name, age);
this.consultationFee = consultationFee;
}
@Override
double calculateBill() {
return consultationFee;
}
}
// Driver class
public class HospitalSystem {
public static void main(String[] args) {
Patient p1 = new InPatient("Ravi", 45, 5, 1500);
Patient p2 = new OutPatient("Anjali", 30, 500);
System.out.println(p1.getName() + "'s Bill: ₹" + p1.calculateBill());
System.out.println(p2.getName() + "'s Bill: ₹" + p2.calculateBill());
}
}
Output:
Ravi's Bill: ₹7500.0
Anjali's Bill: ₹500.0
Example 2: Financial Sector – Bank Transaction System
Problem Statement:
Build a system to handle different types of accounts—SavingsAccount and CurrentAccount—
with common attributes but specific rules for withdrawal and interest calculation.
6 | 13
Java OOP Concepts
Applied Concepts:
Class & Object: Account
Constructor: Set initial balance
Inheritance: SavingsAccount and CurrentAccount inherit Account
Method Overriding: Custom withdrawal behavior
Encapsulation: Private balance with getters/setters
Abstraction: Abstract base account class
Code:
abstract class BankAccount {
private String accountHolder;
protected double balance;
public BankAccount(String accountHolder, double balance) {
this.accountHolder = accountHolder;
this.balance = balance;
}
public String getAccountHolder() { return accountHolder; }
public double getBalance() { return balance; }
abstract void withdraw(double amount);
abstract double calculateInterest();
}
class SavingsAccount extends BankAccount {
private final double interestRate = 0.04;
public SavingsAccount(String name, double balance) {
super(name, balance);
}
@Override
void withdraw(double amount) {
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient balance in Savings Account");
}
@Override
double calculateInterest() {
return balance * interestRate;
}
}
class CurrentAccount extends BankAccount {
7 | 13
Java OOP Concepts
private final double overdraftLimit = 10000;
public CurrentAccount(String name, double balance) {
super(name, balance);
}
@Override
void withdraw(double amount) {
if (balance + overdraftLimit >= amount)
balance -= amount;
else
System.out.println("Withdrawal exceeds overdraft limit");
}
@Override
double calculateInterest() {
return 0; // No interest for current accounts
}
}
// Driver code
public class BankSystem {
public static void main(String[] args) {
BankAccount acc1 = new SavingsAccount("Neha", 10000);
BankAccount acc2 = new CurrentAccount("Amit", 5000);
acc1.withdraw(3000);
acc2.withdraw(13000); // Within overdraft
System.out.println(acc1.getAccountHolder() + " Balance: ₹" +
acc1.getBalance());
System.out.println(acc2.getAccountHolder() + " Balance: ₹" +
acc2.getBalance());
System.out.println("Neha's Interest: ₹" + acc1.calculateInterest());
}
}
Output:
Neha Balance: ₹7000.0
Amit Balance: ₹-8000.0
Neha's Interest: ₹280.0
📘 Summary of Learning from Both Examples:
Concept Applied In
Class/Object All domain models (Patient, Account)
Inheritance Specialized patient/account types
Polymorphism calculateBill(), withdraw() overridden
8 | 13
Java OOP Concepts
Concept Applied In
Encapsulation Balance, patient details kept private
Abstraction Abstract base class for domain behaviors
------------------------------------------------------------------
1. Which of the following is a correct statement about constructors in
Java?
A) Constructors have a return type
B) Constructors can be static
C) Constructors must have the same name as the class
D) Constructors are inherited by subclasses
Answer: C
Explanation: Constructors have the same name as the class and no return type.
2. Which keyword is used to call the superclass constructor from a
subclass?
A) this
B) super
C) base
D) parent
Answer: B
Explanation: super is used to invoke the parent class constructor or access parent class
methods/fields.
3. Which of the following defines method overloading?
A) Same method name, different class
B) Same method name, same parameters
C) Same method name, different parameter list in same class
D) Same method name, different return type only
Answer: C
Explanation: Method overloading requires the same method name but different parameter lists.
4. What is the output of the following code?
class Animal {
9 | 13
Java OOP Concepts
void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); }
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
A) Animal sound
B) Bark
C) Compilation Error
D) Runtime Error
Answer: B
Explanation: This is runtime polymorphism. The sound() method of the Dog class is called.
5. What access modifier should be used to implement encapsulation?
A) public
B) protected
C) private
D) default
Answer: C
Explanation: Variables should be marked private and accessed via public getters/setters.
6. Which of the following can be instantiated directly?
A) Abstract class
B) Interface
C) Concrete class
D) All of the above
Answer: C
Explanation: Only concrete classes can be instantiated. Abstract classes and interfaces cannot.
7. What will happen if a subclass does not override an abstract method
from its superclass?
A) Compilation error
B) It runs with default behavior
10 | 13
Java OOP Concepts
C) Runtime error
D) The method is ignored
Answer: A
Explanation: All abstract methods must be implemented in the subclass, or the subclass must also
be declared abstract.
8. What is the output of the following code snippet?
class A {
int num = 10;
}
class B extends A {
int num = 20;
void display() {
System.out.println(super.num);
}
}
A) 10
B) 20
C) Compilation error
D) 0
Answer: A
Explanation: super.num refers to the num variable of the superclass A.
9. Which of the following is true about method overriding?
A) Overridden method must have a different return type
B) Overridden method must have the same method name and parameters
C) Overridden method must be static
D) Private methods can be overridden
Answer: B
Explanation: For overriding, method name and parameter list must be exactly the same.
10. In which of the following scenarios is method overriding not
possible?
A) Method is static
B) Method is public
C) Method is protected
D) Method is default
11 | 13
Java OOP Concepts
Answer: A
Explanation: Static methods belong to the class and cannot be overridden.
11. Which of the following best defines abstraction?
A) Hiding implementation details and showing only functionality
B) Wrapping data and functions into a single unit
C) Inheriting from multiple classes
D) Writing multiple methods with the same name
Answer: A
Explanation: Abstraction hides complex implementation and exposes only relevant parts to the
user.
12. Which Java feature helps in designing extensible and testable
Selenium automation frameworks using interfaces like WebDriver?
A) Inheritance
B) Abstraction
C) Encapsulation
D) Static binding
Answer: B
Explanation: Selenium’s WebDriver interface is implemented by multiple browser drivers,
leveraging abstraction.
------------------------------------------------------------------
Question 1: Patient Billing System
Problem:
Create a Java class Patient with private fields name, age, and disease. Create two
subclasses:
InPatient: includes number of admitted days and daily rate.
OutPatient: includes consultation fees.
Each subclass must override a method generateBill() to calculate the patient’s total charges.
💡 Use: Class, Constructor, Inheritance, Encapsulation, Method Overriding
12 | 13
Java OOP Concepts
Question 2: Hospital Staff Management (Abstraction Focus)
Problem:
Design an abstract class HospitalStaff with:
Fields: staffId, name, department
Abstract method: calculateSalary()
Create two subclasses:
Doctor with specialization and patient consultation count.
Nurse with shift hours.
Each subclass must implement calculateSalary() based on different rules.
💡 Use: Abstract Class, Constructor, Overriding
Question 3: Basic Banking Operations (Encapsulation + OOP)
Problem:
Design a class BankAccount with the following:
Private fields: accountNumber, holderName, balance
Public methods: deposit(), withdraw(), checkBalance()
Add appropriate constructors and use getters/setters. Ensure that balance cannot be accessed or
modified directly.
💡 Use: Encapsulation, Constructor, Object Creation
Question 4: Loan Processing System (Polymorphism)
Problem:
Create a base class Loan with method calculateInterest(). Then:
Create subclasses HomeLoan, CarLoan, and PersonalLoan
Each subclass overrides calculateInterest() to apply different interest rates.
Write a driver class to demonstrate polymorphic behavior using Loan reference and different loan
types.
💡 Use: Method Overriding, Runtime Polymorphism
13 | 13