Object-Oriented Programming (OOP)
| Site: | Newgate University Minna - Elearning Platform |
| Course: | Computer Programming I |
| Book: | Object-Oriented Programming (OOP) |
| Printed by: | Guest user |
| Date: | Monday, 9 November 2026, 1:21 PM |
1. Definition
OOP organizes code around objects combining data and behavior, using encapsulation, inheritance, polymorphism, and abstraction.
Core Principles
Encapsulation: Hide data; expose via methods.
Inheritance: Reuse code via class hierarchies.
Polymorphism: Same interface, different behaviors.
Abstraction: Model essentials, ignore details.
1.1. Example Java
Example (Java)
abstract class Animal {
private String name; // Encapsulation
public Animal(String name) { this.name = name; }
public abstract String speak(); // Abstraction
public String getName() { return name; }
}
class Dog extends Animal { // Inheritance
public Dog(String name) { super(name); }
@Override
public String speak() { // Polymorphism
return getName() + " says Woof!";
}
}
1.2. Example
public class OOPExample {
public static void main(String[] args) {
Animal dog = new Dog("Buddy");
System.out.println(dog.speak()); // Output: Buddy says Woof!
}
}
Strengths
Intuitive for real-world modeling.
Reusable and maintainable.
Scalable for large systems.
Weaknesses
Abstraction overhead.
Complex hierarchies possible.
Less suited for stateless tasks.
Use Cases
Enterprise apps (Spring).
GUI apps (JavaFX).
Android development.
Languages
Java, C++, C#, Python.
2. Scripting Languages
Definition
Scripting languages are high-level, often interpreted languages for automation, rapid development, or system integration, prioritizing ease over performance.
Core Characteristics
Interpreted: Run without compilation.
Dynamic Typing: Types resolved at runtime.
Lightweight Syntax: Minimal boilerplate.
Integration: Extends other systems.
2.1. Example (Java with JavaScript)
Java supports scripting via the Nashorn engine or GraalVM.
import javax.script.*;
public class ScriptingExample {
public static void main(String[] args) throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String script = "var sum = 0; for (var i = 1; i <= 3; i++) { sum += i; } sum;";
Object result = engine.eval(script);
System.out.println(result); // Output: 6 (1 + 2 + 3)
}
}
JavaScript script runs within Java.
Strengths
Fast prototyping.
Ideal for automation.
Rich ecosystems.
Weaknesses
Slower than compiled languages.
Not for systems programming.
Dynamic typing risks errors.
3. Use Cases
Use Cases
Web scripting (JavaScript).
Automation (Groovy in Java).
System integration.
Languages
JavaScript, Python, Groovy, Bash.
6. Structured Programming Principles
Definition
Structured programming, a subset of the imperative paradigm, uses disciplined control flow to avoid chaotic constructs like "goto," ensuring clear, maintainable code.
Core Principles
Sequence: Instructions executed in order.
Selection: Conditional branching (if-else).
Iteration: Loops (for, while).
Modularity: Methods for reusability.
Example (Java)
3.1. Example (Java)
java
public class StructuredExample {
public static int sumEvens(int n) {
int sum = 0; // Sequence
for (int i = 1; i <= n; i++) { // Iteration
if (i % 2 == 0) { // Selection
sum += i;
}
}
return sum; // Modularity
}
public static void main(String[] args) {
System.out.println(sumEvens(6)); // Output: 12 (2 + 4 + 6)
}
}
Strengths
· Readable and maintainable.
· Reduces errors.
· Foundational for Java.
Weaknesses
Limited for complex paradigms.
Relies on mutable state.
Use Cases
General algorithms.
Procedural code in Java.
3.2. Practical Example: Sum of Squares (1 to n)
Compute the sum of squares (e.g., for n=3: 1 + 4 + 9 = 14).
Comparison of Paradigms
Paradigm | Focus | Control Flow | State Management | Java Use Case |
Functional | Mathematical functions | Implicit (Streams) | Immutable | Stream processing |
Declarative | Desired outcome | System-managed (SQL) | Minimal | JDBC queries |
Logic | Logical inference | Backtracking (tuProlog) | Facts/rules | Expert systems |
OOP | Objects (data + behavior) | Explicit (methods) | Mutable | Enterprise apps |
Structured | Disciplined control flow | Sequence, selection, iteration | Mutable | General algorithms |
Scripting | Automation, rapid tasks | Imperative (JavaScript) | Dynamic | JavaScript via Nashorn |
4. Introduction to Data Types
In programming, data types define the kind of data a variable can hold and the operations that can be performed on it. They are essential for managing data efficiently in any programming language. Basic data types are the fundamental building blocks, providing the foundation for more complex data structures. This lecture covers the primary data types, their characteristics, use cases, and examples across popular programming languages like Python, Java, and C++.
1. Integer
Integers are whole numbers, positive or negative, including zero, without any fractional or decimal component.
Characteristics
Storage: Typically uses 4 bytes (32 bits) in most languages, though sizes can vary (e.g., 2 bytes for short in Java, 8 bytes for long).
Range: Depends on the language and bit size. For a 32-bit signed integer, the range is approximately -2,147,483,648 to 2,147,483,647.
Operations: Addition (+), subtraction (-), multiplication (*), division (/ or //), modulus (%), etc.
No decimal precision: Integers are exact, making them ideal for counting and indexing.
Use Cases
Counting items (e.g., loop counters, quantities).
Array or list indexing.
Representing discrete values like IDs or scores.
Examples
Python: x = 42, y = -10
Java: int x = 42;
C++: int x = 42;
Notes
In Python, integers have unlimited precision (no fixed size limit).
In Java and C++, integers are fixed-size, and exceeding the range causes overflow unless using larger types like long.
4.1. Float/Double
Floating-point numbers (floats or doubles) represent real numbers with decimal points, allowing fractional values.
Characteristics
Storage: Floats typically use 4 bytes (single precision), doubles use 8 bytes (double precision).
Range and Precision: Floats have less precision than doubles; doubles are preferred for high-precision calculations.
Operations: Similar to integers, plus trigonometric functions (e.g., sin, cos) and exponentiation.
Precision Issues: Floats may introduce rounding errors (e.g., 0.1 + 0.2 might yield 0.30000000000000004 in some languages).
Use Cases
Scientific calculations (e.g., physics simulations).
Financial calculations requiring decimals (e.g., prices, percentages).
Graphics and game development for coordinates and measurements.
Examples
Python: x = 3.14, y = -0.001
Java: float x = 3.14f;, double y = -0.001;
C++: float x = 3.14f;, double y = -0.001;
Notes
Use double for higher precision in Java/C++.
Python’s float is equivalent to a double in other languages.
4.2. Boolean
A Boolean data type represents two values: true or false.
Characteristics
Storage: Typically 1 bit (theoretically) but often stored as a byte for alignment in memory.
Operations: Logical operations like AND (&&), OR (||), NOT (! or not).
Immutable: Booleans are simple and cannot hold other values.
Use Cases
Conditional statements (e.g., if statements).
Flags to control program flow (e.g., is_active = true).
Logical comparisons (e.g., x > y).
Examples
Python: is_valid = True, has_error = False
Java: boolean isValid = true;
C++: bool isValid = true;
Notes
In C, there’s no built-in Boolean type (uses 0 for false, non-zero for true), but C99 introduced stdbool.h.
Python’s bool is a subclass of int (True == 1, False == 0).
4.3. Character
A character represents a single symbol, such as a letter, digit, or punctuation mark, typically stored as a numeric code (e.g., ASCII or Unicode).
Characteristics
Storage: 1 byte for ASCII (e.g., C), 2 bytes for Unicode in Java (char).
Range: ASCII (0–127 for basic characters), Unicode (wider range for global scripts).
Operations: Comparison, concatenation (when used in strings), or conversion to numeric codes.
Use Cases
Storing single letters or symbols (e.g., 'A', '#').
Building blocks for strings.
Encoding special characters in text processing.
Examples
Python: c = 'A' (Python treats single characters as strings)
Java: char c = 'A';
C++: char c = 'A';
Notes
Python has no distinct char type; single characters are strings of length 1.
Java’s char is 16-bit Unicode, supporting international characters.
4.4. String
A string is a sequence of characters, used to represent text.
Characteristics
Storage: Varies by language; typically an array of characters plus metadata (e.g., length).
Immutable in some languages (e.g., Java, Python), meaning they cannot be changed after creation.
Operations: Concatenation (+), substring extraction, length calculation, case conversion, etc.
Use Cases
Storing and manipulating text (e.g., names, messages).
User input/output.
Data parsing (e.g., JSON, CSV).
Examples
Python: s = "Hello, World!"
Java: String s = "Hello, World!";
C++: std::string s = "Hello, World!";
Notes
In C, strings are arrays of characters ending with a null terminator (\0).
Python and Java strings are immutable, requiring new strings for modifications.
C++ strings (via std::string) are mutable.
4.5. Additional Data Types
Some languages include other basic types:
Byte: A small integer, typically 8 bits (-128 to 127). Used for low-level data (e.g., file I/O).
Example: Java’s byte b = 100;
Null/None: Represents the absence of a value.
Example: Python’s x = None, Java’s x = null
Void: Used in languages like C/C++ to indicate no return value for functions.
Data Type | Python | Java | C++ |
Integer | int (unlimited) | int, long | int, long |
Float | float (double precision) | float, double | float, double |
Boolean | Bool | boolean | bool |
Character | No distinct type | char | char |
String | str (immutable) | String (immutable) | std::string (mutable) |
4.6. Practices
Best Practices
1. Choose the Right Type: Use integers for counting, floats for decimals, and strings for text to optimize memory and performance.
2. Handle Precision: Be cautious with floats for financial or critical calculations due to rounding errors; consider libraries like Python’s decimal.
3. Type Safety: In statically typed languages (Java, C++), declare types explicitly to avoid errors.
4. Immutability: Understand whether a type (e.g., strings in Python/Java) is immutable to avoid unnecessary operations.
5. Validation: Always validate user input when converting to specific types (e.g., string to integer).
Practical Example
Below is a Python program demonstrating the use of basic data types:
# Integer
age = 25
print(f"Age: {age}")
# Float
height = 5.9
print(f"Height: {height} feet")
4.7. Boolean
is_student = True
print(f"Is student? {is_student}")
# String
name = "Alice"
print(f"Name: {name}")
# Character-like (string of length 1)
initial = "A"
print(f"Initial: {initial}")
Output
Age: 25
Height: 5.9 feet
Is student? True
Name: Alice
Initial: A
4.8. Java code
public class BasicDataTypes {
public static void main(String[] args) {
// Integer
int age = 25;
System.out.printf("Age: %d%n", age);
// Float (using double for better precision, similar to Python's float)
double height = 5.9;
System.out.printf("Height: %.1f feet%n", height);
// Boolean
boolean isStudent = true;
System.out.printf("Is student? %b%n", isStudent);
// String
String name = "Alice";
System.out.printf("Name: %s%n", name);
// Character
char initial = 'A';
System.out.printf("Initial: %c%n", initial);
}
}
4.9. Conclusion
Understanding basic data types is crucial for writing efficient and correct programs. Each type serves a specific purpose, and choosing the appropriate type enhances code readability, performance, and reliability. As you progress, you’ll encounter composite types (e.g., lists, arrays, objects) built upon these fundamentals.
Further Reading
Explore type casting (converting between types, e.g., int("42")).
Learn about composite data types like lists, dictionaries, or structs.
Understand memory management for types in low-level languages like C++.