COS 201 Introduction To Java
COS 201 Introduction To Java
1. INTRODUCTION TO OOP
1.1 What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm, a way of thinking about
programming, that focuses on designing software using “objects.”
i. An object is a self-contained unit that combines data (attributes) and behavior
(methods/functions).
ii. In simpler terms: an object is like a real-world entity. It has properties (characteristics)
and can-do things (actions).
1.2 Key Idea: Software as a Collection of Objects
Instead of writing step-by-step instructions like in procedural programming, OOP encourages
developers to model the software as a set of interacting objects, similar to how things interact in
real life.
Example (Analogy):
Think of a car:
i. Attributes (Data): color, brand, model, speed, fuel level
ii. Behaviors (Methods): start(), stop(), accelerate(), brake()
In OOP, we create a Car class as a blueprint, and each actual car (your friend’s car, your car, a
taxi) becomes an object created from that blueprint.
1.3 Why OOP?
OOP is not just a programming style; it solves real problems in software development. Here’s
why it’s important:
1. Model Real-World Systems
i. Many software systems represent real-world entities: banks, students, hospitals,
stores, vehicles.
ii. OOP lets us directly map real-world objects into code, making programs easier to
understand.
iii. Example: A student management system can have a Student class, a Course
class, and a Lecturer class—just like the real-world system.
2. Improve Modularity
i. Code is broken into self-contained units (classes/objects).
ii. Each object handles its own data and behavior, making programs organized and
manageable.
2
iii. Example: If we want to change how a Car accelerates, we only need to modify
the Car class, not the whole program.
3. Increase Code Reusability
i. Once a class is written, it can be reused to create many objects.
ii. Classes can also be extended to create new classes (inheritance).
iii. Example: A Vehicle class can be reused to create Car, Truck, and Bus
classes with minimal extra code.
4. Make Software Easier to Maintain
i. Because OOP organizes code into logical units, fixing bugs or adding features
becomes easier.
ii. Encapsulation ensures that internal details are hidden, reducing the chance of
breaking other parts of the program.
iii. Example: Changing the internal structure of the Student class doesn’t affect
code that uses Student objects if access is via getters/setters.
1.4 Real-Life Analogy of OOP
Real-World Entity OOP Concept
Car Class
Your Car Object
Color, Brand Attributes
Start(), Stop() Methods
Car blueprint Class Definition
Manufacturing multiple cars Object Instantiation
Think of a class as a recipe. The recipe defines ingredients and instructions (attributes and
methods). Each dish you cook from it is an object. You can make many dishes from the same
recipe.
Summarily,
i. OOP = designing programs using objects
ii. Object = combination of data (attributes) and behavior (methods)
iii. Key benefits: Real-world modeling, modularity, reusability, maintainability
iv. OOP is the foundation of Java, C++, C#, Python (partially), and many modern
programming languages.
Java is a programming language designed with Object-Oriented Programming at its core. Except
for primitive types like int, char, and boolean, everything in Java is treated as an object.
This makes Java ideal for teaching OOP concepts, building reusable software components, and
developing real-world applications.
1.2.1 Key Features and Advantages
1. Platform Independence – “Write Once, Run Anywhere”
i. Java programs are compiled into bytecode, which runs on the Java Virtual Machine
(JVM).
ii. This means the same program can run on Windows, Linux, or Mac without changes.
Example:
You write a Java program on Windows → compile → run it on MacOS
without modification.
Why it matters for OOP: Objects and classes you design in Java can be used across different
platforms seamlessly.
You can focus on building objects and application logic instead of reinventing common features.
Why it matters for OOP: Helps maintain data integrity within your objects and prevents misuse
of class attributes.
Summarily,
a) Java = pure OOP language (except primitives)
b) Advantages for OOP:
i. Platform independence → code reuse across systems
ii. Automatic memory management → safer object creation
5
// getter
public String getName() {
return name;
}
// setter
public void setName(String name) {
[Link] = name;
}
2.2 Inheritance
Inheritance allows a class (child/subclass) to inherit attributes and methods from another class
(parent/superclass).
i. Promotes code reuse
ii. Enables hierarchical relationships
Example
class Vehicle {
String brand;
void start() {
[Link]("Vehicle started");
}
}
2.3 Polymorphism
Polymorphism means “many forms.”
a) A single interface or method can behave differently depending on context.
b) Two common types in Java:
i. Method Overloading – same method name, different parameters
ii. Method Overriding – subclass changes behavior of a method from superclass
Example: Overloading
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
Example: Overriding
class Vehicle {
void start() {
[Link]("Vehicle started");
}
}
2.4 Abstraction
Abstraction is the process of representing essential features of an object while hiding
unnecessary implementation details.
8
b) ClassName – the name of the class (should start with a capital letter by convention)
c) Inside curly braces {}:
i. Fields – store object data
ii. Methods – define object behavior
3.3 Example: A Simple Student Class
class Student {
String name; // attribute
int age; // attribute
String department; // attribute
Analogy:
i. Student class = plan for a student
ii. Attributes = student’s details
iii. Method = actions student can perform
Encapsulation means:
i. Wrapping data (attributes/fields) and methods (functions) inside a class
ii. Restricting direct access to the internal data
iii. Providing access only through controlled methods (getters and setters)
Key Idea:
i. The internal representation of an object is hidden from the outside.
ii. Only authorized methods can read or modify the data.
How to Achieve Encapsulation in Java
i. Declare fields as private – prevents external access
ii. Provide public getter and setter methods – allows controlled access
private int age; // hidden
public int getAge(){} // controlled access
public void setAge(int a){} // controlled modification
}
}
}
Explanation:
i. private String name and private int age → these variables cannot be
accessed directly outside the class
ii. getName() and setName() → provide controlled access to name
iii. setAge()
→ includes validation to prevent invalid data (e.g., negative age)
Usage Example:
public class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]("Amarachi"); // set name using setter
[Link](19); // set age using setter
Real-Life Analogy
1. Think of a capsule medicine:
i. Inside it is medicine (data)
ii. You cannot access the medicine directly; you only take it as instructed (methods)
2. This protects the medicine from misuse, just as encapsulation protects your object’s data.
5. METHODS
In Java, methods are the building blocks of behavior. They define what an object can do.
5.1 What is a Method?
A method is a block of code that performs a specific task.
i. Think of it as a function inside a class.
ii. Methods operate on objects or data, and they may return a result or perform an action.
Analogy:
1. A method is like a kitchen appliance:
i. Blender → mixes ingredients
ii. Toaster → toasts bread
2. You call the appliance to perform its action, just like you call a method in Java.
Explanation:
i. public → access modifier (method can be called from anywhere)
ii. int → return type (method returns an integer)
iii. add → method name
iv. (int a, int b) → parameters (inputs)
v. return a + b; → performs addition and returns the result
Usage Example:
public class Calculator {
public int add(int a, int b) {
return a + b;
16
Output:
Sum = 30
6. CONSTRUCTORS
Constructors are special methods in Java designed to initialize objects when they are created.
6.1 What is a Constructor?
A constructor is a special type of method used to initialize the state of an object (i.e., assign
values to its attributes) when it is created.
Characteristics of Constructors
1. Same name as the class
i. Ensures the compiler recognizes it as a constructor
2. No return type
i. Unlike regular methods, constructors do not return any value, not even void
3. Called automatically
i. When an object is created using the new keyword, the constructor executes
automatically
17
Analogy
1) Think of a constructor as a factory machine that prepares a product:
i. The blueprint (class) exists
ii. When you press the “start” button (create an object), the machine automatically
sets up all initial components according to the blueprint
2) Example:
i. A Car class → constructor automatically sets color, model, and fuel level when a
new car object is created
6.2 Types of Constructors in Java
1. Default Constructor
i. Provided automatically by Java if you do not define any constructor
ii. Initializes object with default values
iii. Example: numeric fields → 0, boolean → false, objects → null
2. No-argument Constructor
i. Defined explicitly by the programmer
ii. Takes no parameters
iii. Example:
class Student {
String name;
int age;
// No-argument constructor
Student() {
name = "Unknown";
age = 0;
}
}
3. Parameterized Constructor
i. Defined explicitly with parameters to initialize attributes
ii. Example:
18
class Student {
String name;
int age;
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
}
Usage Example:
public class Main {
public static void main(String[] args) {
// Using no-argument constructor
Student s1 = new Student();
[Link]([Link] + " - " + [Link]); // Output:
Unknown - 0
Explanation
Method Signature What it does
add(int a, int b) Adds two integers
add(double a, double b) Adds two decimal numbers
add(int a, int b, int c) Adds three integers
20
Usage Example:
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
Output:
30
31.0
6
Visual Analogy
Imagine a Swiss Army knife:
i. One tool name → “cut”
ii. Multiple blades → small blade, large blade, scissors
iii. Same action name, different ways of performing it
21
// Deposit method
public void deposit(double amount) {
balance += amount;
}
// Withdraw method
public void withdraw(double amount) {
if(amount <= balance) {
balance -= amount;
} else {
[Link]("Insufficient funds");
}
}
// Check balance
public double getBalance() {
return balance;
}
}
[Link](300); //
withdraw funds
[Link]("Final Balance: " + [Link]());
}
}
Explanation
1. Encapsulation
i. accountNumber and balance are private fields
ii. They cannot be accessed directly outside the class
iii. Access is provided through methods (deposit, withdraw, getBalance)
2. Constructor
i. BankAccount(String accNumber, double initialBalance)
initializes the object automatically when created
3. Methods
i. deposit(double amount) → adds money to the balance
ii. withdraw(double amount) → subtracts money if sufficient funds are
available
iii. getBalance() → returns the current balance
4. Object Creation
i. BankAccount b = new BankAccount("12345", 1000);
ii. This creates an object of BankAccount with an account number and initial
balance
5. Performing Actions
i. [Link](500) → increases balance to 1500
ii. [Link](300) → decreases balance to 1200
iii. [Link]() → prints the final balance
Output:
Final Balance: 1200.0
23
Object b
Real-Life Analogy
i. BankAccount class = blueprint for any bank account
ii. Object b = your personal bank account
iii. Deposit/Withdraw methods = teller transactions
iv. Encapsulation = your account balance is private; only the bank’s system (methods) can
update it
[Link]();
[Link]();
}
}
Concepts Practiced: Classes, objects, methods, attributes
// Parameterized constructor
Rectangle(double l, double w) {
length = l;
width = w;
}
double area() {
return length * width;
}