COS202: Advanced Object-Oriented Programming in Java Study Guide
COS202 Computer Programming II: Course Overview
- Course Code: COS202
- Course Title: Computer Programming II
- Units: 3 Credits (LH 30; PH 45)
- Course Content Coverage:
- Advanced Object-Oriented Programming (OOP) including polymorphism, abstract classes, and interfaces.
- Class hierarchies and program organization using packages and namespaces.
- Use of API: Iterators/enumerators, List, Stack, and Queue.
- Algorithms: Searching, sorting, and recursive algorithms.
- Event-driven programming: Event-handling methods and event propagation.
- Exception handling and Applications in Graphical User Interface (GUI) programming.
- Lab Work Focus: Problem-solving and program development, static and dynamic data structures, searching and sorting (iterative and recursive), and GUI programming.
- Learning Outcomes:
- Demonstrate principles of good and structured programming.
- Master string processing, internal searching, sorting, and recursion.
- Utilize OOP concepts: classes, objects, inheritance, polymorphism, and data abstraction.
- Apply tools for developing, compiling, interpreting, and debugging programs.
- Utilize syntax, data objects, operators, flow constructs, Arrays, methods, Exceptions, Applets, and the Abstract Window Toolkit.
- Reference Textbooks:
- Object Oriented Programming and Java by Danny Poo, Derek Kiong, and Swarnalatha Ashok.
- Java How To Program (9ed.) by Deitel.
- Course Developer: Dr. Femi E. Ayo, Olabisi Onabanjo University.
Basic Object-Oriented Programming (OOP) Concepts
- Definition: OOP is a programming paradigm based on objects (containing data and methods) aimed at incorporating modularity and reusability. It decomposes problems into entities called objects and builds data and methods around them.
- Characteristics of OOP:
- Bottom-up approach in program design.
- Programs organized around objects grouped into classes.
- Focus on data with methods operating on that data.
- Interaction between objects through methods.
- Enhanced abstraction (modeling data and methods together).
- Better maintainability (less fragile, more comprehensible).
- Better reusability via class inheritance.
- OOP Languages: Examples include C++, Java, Smalltalk, Delphi, C#, Perl, Python, Ruby, and PHP.
- Procedure-Oriented Programming (POP): Problem-solving is viewed as a sequence of tasks/functions. Heavy focus on functions with little attention to data. Examples: COBOL, FORTRAN, PASCAL, and C.
Comparison: POP vs. OOP
| Feature | Procedure Oriented Programming (POP) | Object-Oriented Programming (OOP) |
|---|
| Division | Program is divided into small parts called functions. | Program is divided into parts called objects. |
| Focus | Focuses on functions and sequence of actions. | Focuses on data rather than procedures (models real world). |
| Approach | Top-Down approach. | Bottom-Up approach. |
| Access Specifiers | No access specifiers. | Public, Private, Protected etc. |
| Data Movement | Data moves freely from function to function. | Objects communicate via member functions. |
| Expansion | Adding new data/functions is difficult. | Easy to add new data and functions. |
| Data Access | Uses global data shared by functions. | Data is controlled (public or private). |
| Security | No proper data hiding; less secure. | Supports data hiding for high security. |
| Overloading | Not possible. | Function and Operator overloading is possible. |
| Examples | C, VB, FORTRAN, Pascal. | C++, Java, VB.NET, C#.NET, Python. |
Benefits of OOP
- Reusability: Code written by one user can be reused by others without modification.
- Inheritance: Eliminates redundant code and extends existing classes.
- Data Hiding: Programmers can hide data and functions within a class to build secure programs.
- Reduced Complexity: Problems are viewed as a collection of objects responsible for specific tasks.
- Maintenance: Easy to upgrade and maintain; complexity is manageable.
- Message Passing: Facilitates easier interfacing with external systems.
- Modifiability: Changes inside a class do not affect other parts of the program due to public method interfaces.
Java Language Overview and Environment
- History: Developed at Sun Microsystems in 1991 by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan. Designed to be platform-independent.
- Paradigm: Based on OOP; derived from C syntax (curly braces
{}, variables declared before use). - Structure: Java programs start with packages (namespaces), containing classes, which contain methods, variables, and constants.
- Environment Setup:
- Download Java Development Kit (JDK).
- Install the JDK (.exe).
- Install an Integrated Development Environment (IDE) or text editor.
- Files are saved with the
.java extension. - The Java Compiler produces Java bytecodes (
.class files). - The Java Virtual Machine (JVM) interprets bytecodes into machine language.
- Popular IDEs/Editors: Notepad, BlueJ, NetBeans (open-source), JCreator, Eclipse, IntelliJ IDEA, and JBuilder.
Java Basic Syntax and Coding Conventions
- Standard Printing Program:
java
public class Welcome1 {
public static void main(String[] args) {
System.out.println("Welcome to Java Programming!");
}
}
- Comments:
- Single-line: Starts with
// and ends at the line terminal. - Multi-line: Starts with
/* and ends with */. - Javadoc: Starts with
/** and ends with */; used for generating HTML documentation (supports tags like @author and @version).
- Class Declaration: Introduced by the keyword
class. By convention, class names use PascalCase (starts with uppercase, e.g., SampleClassName). - Identifiers: Series of characters (letters, digits,
_, $). Significant rules:- Cannot begin with a digit.
- Cannot contain spaces.
- Case-sensitive (
Value and value are different). - Keywords cannot be used as identifiers.
- Main Method: The entry point for JVM. Signature:
public static void main(String[] args). Keyword void denotes no return value. - Output:
System.out is the standard output object. System.out.println() prints a line and moves the cursor to the next line. - Case Sensitivity: Java is strictly case-sensitive.
- Naming Conventions:
- Class Names: UpperCase (e.g.,
MyFirstJavaClass). - Method Names: CamelCase starting with lowercase (e.g.,
myMethodName()). - File Name: Must exactly match the class name (including case) with a
.java extension.
Java Modifiers and Keywords
- Access Modifiers:
default, public, protected, private. - Non-access Modifiers:
final, abstract, strictfp. - Reserved Keywords: Constants or identifiers cannot use these. Examples include:
abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while.
Data Types and Variables
- Variable Declaration: Named storage with size, layout, and operations determined by type. Syntax:
int a = 10, b = 10;, double pi = 3.14159;. - Primitive Data Types (8):
- Byte: 8-bit signed two’s complement integer.
- Short: 16-bit signed two’s complement integer.
- Int: 32-bit signed two’s complement integer.
- Long: 64-bit signed two’s complement integer.
- Float: Single-precision 32-bit IEEE 754.
- Double: Double-precision 64-bit IEEE 754.
- Boolean: Represents one bit of information.
- Char: Single 16-bit Unicode character.
- Reference/Object Data Types: Created using constructors (e.g.,
Animal animal = new Animal("giraffe");).- Default value is
null. - Includes class objects and arrays.
- Kinds of Variables:
- Local Variables: Declared in methods/blocks. Created on entry, destroyed on exit. No access modifiers. No default values (must be initialized).
- Instance Variables: Declared inside a class but outside methods. Created with
new, destroyed with object. Accessible by all class methods. Recommended to be private. Default values: 0 for numbers, false for boolean, null for references. - Class/Static Variables: Declared with
static keyword. Only one copy per class. Created at program start, destroyed at program stop. Accessed via ClassName.VariableName.
Operators
- Arithmetic:
+, -, *, /, %, ++, --. - Relational:
==, !=, >, <, >=, <=. - Logical:
&&, ||, !. - Bitwise: Operates on bits (
&, |, ^, ~). - Assignment:
=, +=, -=, *=, /=, %=. - Misc Operators:
- Conditional (Ternary):
variable x = (expression) ? value if true : value if false;. - instanceof: Checks if an object is of a specific type. Example:
name instanceof String.
Control Structures
- Transfer of Control: Non-sequential execution.
- Sequence Structure: Statements executed in order.
- Selection Structures:
- if: Single-selection.
- if…else: Double-selection.
- switch: Multiple-selection. Requires
break to exit the structure after a case is processed. The default case is optional.
- Repetition Structures (Loops):
- while: Tests condition at the start (0 or more executions).
- do…while: Tests condition at the end (executes at least once).
- for: Counter-controlled. Format:
for(initialization; condition; increment) { body }. - Enhanced for: Iterates through arrays without counters. Syntax:
for (parameter : arrayName) { ... }.
- Flow Keywords:
- break: Immediate exit from a loop or switch.
- continue: Skips the rest of the loop body and proceeds to the next iteration.
Core Principles of OOP
- Encapsulation: Making fields
private and providing access through public getters and setters. Acts as a protective barrier/Data Hiding. - Abstraction: Hiding complexity. Uses
abstract classes and methods.- Abstract Class: Cannot be instantiated; used as a superclass.
- Abstract Method: Method signature without a body (
public abstract void draw();).
- Polymorphism: Ability of an object to take many forms (e.g., a
Deer is an Animal, and a Vegetarian, and a Deer). - Method Overloading: Multiple methods in a class with the same name but different parameters (number or type).
- Inheritance: One object acquires properties of another. Keywords:
extends (for classes) and implements (for interfaces).- IS-A Relationship: Parent-child relationship.
- HAS-A Relationship (Aggregation): A class having an entity reference to another class (e.g., an
Employee has an Address).
- Packages: Grouping of similar classes and interfaces. Removes naming collisions and provides access protection.
- Compilation:
javac -d . FileName.java. - Running:
java packagename.ClassName. - Importing:
import pack.* (all classes) or import pack.A (specific class).
- Interfaces: A blueprint of a class containing static constants and abstract methods. Achieves full abstraction and multiple inheritance. Fields are
public static final by default; methods are public abstract. Marker/Tagged interfaces (e.g., Serializable) have no members.
Exception Handling
- Definition: Mechanism to handle runtime errors and maintain normal application flow. Errors spawn a "stack trace".
- Keywords:
try, catch, finally, throw, throws. - The try-catch-finally Block:
try: Encloses code that might throw an exception.catch: Handles specific exceptions.finally: Executes code regardless of whether an exception occurred (used for resource cleanup like closing files).
- Checked vs. Unchecked Exceptions:
- Checked: Verified at compile-time (e.g.,
IOException). Inherit from Exception but not RuntimeException. - Unchecked: Verified at runtime (e.g.,
ArithmeticException, NullPointerException). Inherit from RuntimeException. - Errors: Irrecoverable JVM conditions (e.g.,
OutOfMemoryError).
- Scenarios:
- ArithmeticException: Division by zero in integer arithmetic.
- InputMismatchException: Scanner receiving non-matching data type.
- NullPointerException: Operation on a null variable.
- NumberFormatException: Invalid string-to-number conversion.
- ArrayIndexOutOfBoundsException: Invalid array index access.
- Throw vs. Throws:
throw: Used to explicitly throw an instance of an exception within a method.throws: Declared in a method signature to indicate which exceptions the method might throw.
Arrays
- Definition: A group of variables (elements) of the same type. Arrays are objects/reference types.
- Indexing: Zero-indexed (0 to length−1).
- Declaration:
int[] array = new int[10]; or using an initializer list {32, 27, 64}. - Multidimensional Arrays: Represented as arrays of arrays.
- Creation:
int[][] b = new int[3][4];. - Ragged Arrays (different row lengths):
int[][] b = new int[2][]; b[0] = new int[5]; b[1] = new int[3];.
- Scanner Class: Part of
java.util. Uses nextInt(), nextDouble(). Requires System.in. - BufferedReader Class: Part of
java.io. Requires InputStreamReader. Uses readLine() (must be inside try-catch for IOException). - JOptionPane: Part of
javax.swing. Uses dialog boxes:showInputDialog("Prompt")showMessageDialog(null, "Message")
Laboratory Exercises and Programming Tasks
- Matrix Operations: Accept two matrices and perform addition, subtraction, or multiplication via a switch menu.
- Array Statistics: Calculate min, max, range, mode, median, mean, variance, and standard deviation for an input array.
- Square Class: Side length variable, constructor, enlargement methods, and area computation.
- Random Squares: Sum of areas of 10 randomly sized squares using
Math.random(). - ASCII Drawing: Functionality for a Square to draw itself using characters (e.g.,
* or X). - Divisibility Puzzle: Find a 9-digit number d1d2...d9 where the prefix of length n is divisible by n.
- Calculator: Design a simple calculator using OOP features.
- Min/Max: Read 5 integers and output the largest and smallest.
- Multiples: Read 2 integers and check if the first is a multiple of the second via
%. - Getters/Setters Logic: Explanation of why access control is important for instance variables.
- Employee Class: Name and monthly salary (validated positive). Calculate yearly salary and apply a 10% raise.
- Date Class: Month, day, year variables;
displayDate method formatted as m/d/y. - Invoice Class: Part number, description, quantity, price. Method
getInvoiceAmount. Validate quantity/price (set to 0 if negative). - Integer Division: Explain the loss of fractional parts and how to avoid it (using
float/double). - Gross Pay Calculator: Straight time for first 40 hours, then time-and-a-half for excess hours.
- Hollow Square: Printing a hollow asterisk square of user-defined size (1−20).
- Palindrome: Check if a 5-digit integer reads the same forward and backward.
- Graphics Drawing: Utilize
drawRect and drawOval based on user menu choice. - Pythagorean Triples: Triple-nested loop to find triples for sides up to 500 (a2+b2=c2).
- isMultiple Method: Return
true if the second integer is a multiple of the first. - isEven Method: Boolean check for even integers using remainder operator.
- Unique Value Array: Read 5 numbers (10−100) and display only non-duplicates.
- Quadrilateral Hierarchy: Inheritance chain:
Quadrilateral -> Trapezoid -> Parallelogram -> Rectangle -> Square. Using a Point class for coordinates and area computation.