0% found this document useful (0 votes)
12 views15 pages

OOP Lecture Notes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views15 pages

OOP Lecture Notes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lecture Notes: Aysha Safdar,

Object Oriented Programming (Theory) Lecturer CS/AI.


NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
Lecture 1 — Class, Default Constructor, Objects, Data Members & Methods
Class
A blueprint or template that defines the structure (fields/data members) and behavior
(methods) of objects.

Object
An instance of a class — created at runtime using new. It holds state (data) and can perform
behavior (methods).

Data Member / Field


A variable defined inside a class that stores information/state.
Example: name, age, price.

Method
A function defined inside a class that describes behavior.
Example: showDetails().

Constructor
A special method used to initialize an object.

 Same name as the class


 No return type (not even void)

Default Constructor

 A constructor with no parameters.


 If we don’t write any constructor, the Java compiler automatically provides one.

Example:

[Link]

// Class definition

public class Student {

// Data members (fields)

public String name;

public int age;

1
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
// Default constructor (no parameters)

public Student() {

// Empty constructor - no default values

// Compiler will run this when object is created

// Method

public void showDetails() {

[Link]("Name: " + name + ", Age: " + age);

[Link]

public class Demo {

public static void main(String[] args) {

// Create object using default constructor

Student s1 = new Student();

// Assign values to data members using dot operator

[Link] = "Ali";

[Link] = 20;

// Call method to display values

[Link]();

// Output: Name: Ali, Age: 20

// Another object

Student s2 = new Student();

2
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
[Link] = "Aisha";

[Link] = 22;

[Link]();

// Output: Name: Aisha, Age: 22

Student Tasks

Task 1: Book Class

 Create a class called Book with the following data members:


o title (String)
o author (String)
o price (double)
 Add a default constructor (empty).
 Add a method printInfo() that prints the book details.
 In main:
1. Create two Book objects using the default constructor.
2. Assign values to their data members using the dot operator.
3. Call printInfo() for both.

Expected Output Example:

Title: Java Basics, Author: John Smith, Price: 500.0


Title: Python for Beginners, Author: Ali Khan, Price: 350.0

Task 2: Student Class

 Create a class called Student with the following data members:


o rollNo (int)
o name (String)
o cgpa (double)
 Add a default constructor (empty).
 Add a method display() that prints student details.
 In main:
1. Create three student objects.

3
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
2. Assign values (rollNo, name, cgpa) using the dot operator.
3. Call display() for each student.

Expected Output Example:

Roll No: 101, Name: Aisha, CGPA: 3.5


Roll No: 102, Name: Bilal, CGPA: 2.8
Roll No: 103, Name: Sara, CGPA: 3.9

Lecture 2 — Constructor Types, Overloading, and the this Keyword

“this” Keyword

 this is a reference variable in Java.


 It always refers to the current object — the object whose method or constructor is
being executed.
 Think of this as "me, the current object."
 Used when parameter names are the same as data members.

 Example:

public class Student {


int rollNo;
String name;
double cgpa;

// Constructor using this


public Student(int rollNo, String name, double cgpa) {
[Link] = rollNo; // '[Link]' is field, 'rollNo' is parameter
[Link] = name;
[Link] = cgpa;
}

public void display() {


[Link]("Roll No: " + rollNo + ", Name: " + name + ", CGPA: " + cgpa);
}
}

Constructor Types

4
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
1. Default Constructor

 A constructor with no parameters.


 If you don’t define one, Java provides a compiler-generated default constructor.

public Student() {
[Link] = 0;
this. name = "Unknown";
[Link] = 0.0;
}

2. Parameterized Constructor

 Accepts parameters to initialize object data members.

public Student(int r, String n, double c) {


[Link] = r;
[Link] = n;
[Link] = c;
}

3. Copy Constructor

 Creates a new object using another object of the same class.

public Student(Student other) {


this. rollNo = [Link];
[Link] = [Link];
[Link] = [Link];
}

2) Constructor Overloading

 Multiple constructors in the same class with different parameter lists.


 Example:
o Student() → no arguments
o Student(int, String) → 2 arguments
o Student(int, String, double) → 3 arguments

5
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
Student Tasks

Activity 1: Employee Class

 Create a class Employee with fields: id, name, salary.


 Write constructors:
1. Default → set 0, "Unknown", 0.0.
2. 3-arg → set id, name, salary.
3. Copy constructor → copy values.
 Add display() and test all constructors in main.

Activity 2: BankAccount Class

 Create a class BankAccount with fields: accNo, owner, balance.


 Write 3 constructors:
1. Default → set "000", "Unknown", 0.0.
2. Parameterized → set all fields.
3. Copy constructor.
 Add methods: deposit(amount) and withdraw(amount).
 In main, create objects with different constructors and test transactions.

Lecture 3 – Static Variables and Static Methods

1) Static Variables

Use a static variable when:

 The value is common for all objects of the class.


 You want one shared copy in memory (saves space).

Examples:

 University name (all students belong to the same university).


 Company name (all employees work in the same company).
 Interest rate (all bank accounts use the same interest rate).
 Counter (to count how many objects have been created).

Avoid static if the value should be different for each object (like roll number, salary, balance).

2) Static Methods

Use a static method when:

6
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
 The method performs a task not dependent on object state.
 You want to call it without creating an object.
 It only uses static variables (not instance variables).

Examples:

 [Link](), [Link]() (utility functions).


 [Link]() (affects all accounts).
 [Link]() (affects all employees).

Avoid static when the method depends on instance data (this), e.g., calculateSalary() for an
employee.

Example 1

[Link]

class Student {
int rollNo; // unique per student
String name; // unique per student
static String university=”Unknown”; // same for all students

public Student(int r, String n) {


this. rollNo = r;
[Link] = n;
}

public void showDetails() { // instance method


[Link](rollNo + " " + name + " " + university);
}

public static void changeUniversity(String newUni) { // static method


university = newUni;
}
}

[Link]

public class Test {


public static void main(String[] args) {
[Link]("ABC University"); // called without object

Student s1 = new Student(1, "Ali");

7
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
Student s2 = new Student(2, "Aisha");

[Link]();
[Link]();
}
}
Example 2

[Link]

public class Student {

int rollNo; // instance variable

String name; // instance variable

static int count = 0; // static variable (shared among all objects)

// 1. Default Constructor

public Student() {

[Link] = 0;

[Link] = "Not Assigned";

count++; // increase when object created

// 2. Parameterized Constructor

public Student(int r, String n) {

[Link] = r;

[Link] = n;

count++;

// 3. Copy Constructor

public Student(Student s) {

8
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
[Link] = [Link];

[Link] = [Link];

count++;

// Instance method

public void display() {

[Link]("RollNo: " + rollNo + ", Name: " + name);

// Static method

public static void showCount() {

[Link]("Total Students Created: " + count);

[Link]

public class TestStudent {

public static void main(String[] args) {

// Using Default Constructor

Student s1 = new Student();

[Link]();

// Using Parameterized Constructor

Student s2 = new Student(101, "Ali");

[Link]();

9
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------

// Using Copy Constructor

Student s3 = new Student(s2);

[Link]();

// Show total objects created

[Link](); // Output: 3

Output Example

RollNo: 0, Name: Not Assigned

RollNo: 101, Name: Ali

RollNo: 101, Name: Ali

Total Students Created: 3

Student Tasks:

Task 1

 Create a class Employee with:


 Instance variables: id, name.
 Static variable: companyName = "TechSoft".
 Constructor to initialize employees.
 Method display() to print employee details.
 Static method changeCompany(String newName) to update company name.

In main:

 Create 2–3 employees.


 Print details.
 Change company name once (using static method).
 Print details again → observe that all employees’ company name changed.

10
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
Task 2

 Create a class Book with:


 Instance variables: title, author.
 Static variable: count = 0.
 Constructor to initialize book details and increment count.
 Method display() to show book details.
 Static method showCount() to display how many books were created.

In main:

 Create 3 book objects.


 Display details of each.
 Show total number of books created using showCount().

Task 3

Class Name: BankAccount

1. Data Members (Instance variables):


o accountNumber (int) – unique for each account, auto-assigned.
o owner (String) – account holder’s name.
o balance (double) – amount in the account.
2. Static Member:
o count (int) – keeps track of how many accounts have been created.
3. Constructors:
o Parameterized constructor to initialize owner and balance.
o Inside constructor → increment count and assign it to accountNumber.
4. Methods:
o deposit(double amount) → add money to the account.
o withdraw(double amount) → subtract money only if balance is sufficient,
otherwise show “Transaction failed: Insufficient balance”.
o showDetails() → display account details (account number, owner, balance).
o showTotalAccounts() → static method that shows how many accounts have been
created.

In main

1. Create two accounts:


o Account 1: Owner = Ali, Balance = 5000
o Account 2: Owner = Aisha, Balance = 10000
2. Perform transactions:

11
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
Ali deposits 2000.
o
Aisha withdraws 3000 (should succeed).
o
Aisha tries to withdraw 8000 (should fail with error message).
o
3. Display details of both accounts.
4. Show total number of accounts created using the static method.

Lecture 4 – Encapsulation in Java (with Access Modifiers, Accessors & Mutators)

What is Encapsulation?

Encapsulation = binding data (variables) and methods (functions) into one unit (class) and
restricting direct access to that data.

 Variables → usually declared private.


 Access → given through public methods (getters and setters).
 This ensures data security and control.

Why Encapsulation?

 Data Hiding – sensitive fields are not directly accessible.


 Validation – setters can restrict invalid values.
 Maintainability – only public methods interact with private data.
 Flexibility – internal implementation can change without affecting external code.

3. Access Modifiers in Java

Access Modifiers define who can access a class, method, or variable.

Specifier Same Same Subclass (same Subclass (other Other


Class Package pkg) pkg) Package
public ✅ ✅ ✅ ✅ ✅
protected ✅ ✅ ✅ ✅(via inheritance) ❌
default ✅ ✅ ✅ ❌ ❌
private ✅ ❌ ❌ ❌ ❌

In encapsulation:

 Fields → private
 Methods (getters/setters) → public

Accessors and Mutators (Getter & Setter Methods)

12
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
 Accessor (Getter): Reads value of private variable.
o Example: getName(), getBalance()
 Mutator (Setter): Updates value of private variable.
o Example: setName(String n), setBalance(double b)

Accessor = read only | Mutator = write/update

Example Without Encapsulation

Public class Student {


String name; // default access
int age;
}

public class Test {


public static void main(String[] args) {
Student s = new Student();
[Link] = "Ali";
[Link] = -5; // ❌invalid but allowed
[Link]([Link] + " " + [Link]);
}
}

Problem: No data protection. Anyone can assign invalid values.

Example With Encapsulation

class Student {
private String name; // private field
private int age;

// Accessor (Getter)
public String getName() {
return name;
}

// Mutator (Setter)
public void setName(String n) {
name = n;
}

// Accessor (Getter)
public int getAge() {

13
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
return age;
}

// Mutator (Setter with validation)


public void setAge(int a) {
if (a > 0) {
age = a;
} else {
[Link]("❌Invalid Age. Must be positive.");
}
}
}

public class TestEncapsulation {


public static void main(String[] args) {
Student s = new Student();

[Link]("Ali"); // Mutator
[Link](20); // Mutator
[Link]("Name: " + [Link]() + ", Age: " + [Link]()); // Accessor

[Link](-5); // ❌Invalid → rejected


}
}

Student tasks:

Task 1: Student Registration System

Scenario:
The university is developing a registration system. Each student has an ID, Name, and Age. For
privacy and correctness:

 The data should be private.


 It should only be changed via public setters and retrieved via public getters.
 Age must always be greater than 0.
 showStudentInfo() → displays all student details in a forma ed way.
 isAdult() → returns true if the student’s age is 18 or above, otherwise false.

Task:

14
Lecture Notes: Aysha Safdar,
Object Oriented Programming (Theory) Lecturer CS/AI.
NUML H9, Islamabad
-----------------------------------------------------------------------------------------------------------------------------------------
 Create a Student class with encapsulated fields, accessors, mutators, and the above
concrete methods.
 In main(), create multiple students, update details, and check if they are adults.

Task 2: Employee Payroll System (Mix of Public & Private)

Scenario:
A company is managing payroll. Each employee has:

 Private fields: id, name, salary


 Public field: companyName (same for all employees)
 Salary must be greater than 0.
 giveBonus(double amount) → increases the employee’s salary by the given bonus.
 displayEmployeeInfo() → prints the employee’s details including company name.

Task:

 Create an Employee class with encapsulated fields, accessors, mutators, and the above
methods.
 In main(), create at least two employees, give them bonuses, and display updated
details.

Task 3: Bank Account Management

Scenario:
A bank needs a secure system to manage customer accounts. Each account has an account
number and a balance, which must remain private. The balance cannot be modified directly—
money can only be added through valid deposits (amount > 0) or withdrawn if sufficient funds
exist.

The system should also allow transferring money between accounts and printing a simple
statement showing the account number and current balance.

Design a BankAccount class that follows these rules, then create accounts in the main program
to perform deposits, withdrawals, transfers, and print statements after each operation.

15

You might also like