@Override
public void update(int newCount) {
System.out.println("Count: " + newCount);
}
}
// Controller
public class CounterController {
private CounterModel model;
public CounterController(CounterModel model) {
this.model = model;
}
public void handleIncrement() {
model.increment();
}
}
// Usage
public class Main {
public static void main(String[] args) {
CounterModel model = new CounterModel();
CounterView view = new CounterView();
CounterController controller = new CounterController(model);
model.addObserver(view);
controller.handleIncrement(); // Updates View: Count: 1
controller.handleIncrement(); // Updates View: Count: 2
}
}
Commands as Methods and as Objects
Commands as Methods
A command is represented by a method in a class.
Directly tied to the class and less flexible.
Example:
java
class Light {
public void turnOn() {
System.out.println("Light is ON");
}
public void turnOff() {
System.out.println("Light is OFF");
}
}
// Usage
Light light = new Light();
light.turnOn();
Commands as Objects
Encapsulates a request as an object, decoupling the invoker from the receiver.
Enables storing, queuing, and executing commands dynamically.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/17
Command Pattern Example:
java
// Command Interface
interface Command {
void execute();
}
// Concrete Command
class TurnOnCommand implements Command {
private Light light;
public TurnOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOn();
}
}
// Invoker
class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
// Usage
public class Main {
public static void main(String[] args) {
Light light = new Light();
Command turnOn = new TurnOnCommand(light);
RemoteControl remote = new RemoteControl();
remote.setCommand(turnOn);
remote.pressButton(); // Output: Light is ON
}
}
Implementing Object-Oriented Language Features
1. Encapsulation:
Achieved using access modifiers (`private`, `protected`, `public`) and encapsulating state in
classes.
Example: Use of getters and setters.
2. Polymorphism:
Implemented through method overloading and method overriding.
Example: Abstract classes and interfaces support runtime polymorphism.
3. Object Identity:
Managed automatically by the language runtime. Objects have a unique memory
address/reference.
4. Memory Management:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/17
In modern OO languages, memory management is mostly automatic (e.g., garbage collection
in Java, Python).
Explicit memory management is used in languages like C++ through `new` and `delete`.
Memory Management
Memory management refers to the process of allocating, using, and deallocating memory during a
program's lifecycle.
Automatic Memory Management (e.g., Java, Python)
Garbage Collection:
Detects and reclaims unused memory (objects with no references).
Techniques: Reference counting, mark-and-sweep, generational GC.
Manual Memory Management (e.g., C++)
Developers explicitly allocate (`new`) and deallocate (`delete`) memory.
Prone to issues like memory leaks and dangling pointers.
Example in C++:
cpp
class MyClass {
public:
MyClass() { std::cout << "Object created.\n"; }
~MyClass() { std::cout << "Object destroyed.\n"; }
};
int main() {
MyClass* obj = new MyClass(); // Allocating memory
delete obj; // Deallocating memory
return 0;
}
Best Practices
Use smart pointers in C++ for safer memory management (`std::shared_ptr`, `std::unique_ptr`).
Minimize object creation/destruction in performance-critical sections.
Avoid cyclic references in languages with automatic garbage collection.
Summary
The MVC pattern separates concerns into Model, View, and Controller, improving modularity.
Commands as methods are simpler, but as objects, they offer flexibility and decoupling.
OO features like encapsulation, polymorphism, and memory management are implemented
through classes, access control, and automated/manual memory mechanisms.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/17
Generic Types and Collections
Generic Types
Generics allow classes, interfaces, and methods to operate on a specified type, providing type
safety and reusability without requiring type casting.
Syntax: `<T>` is used to define a generic type.
Example: A Generic Class
java
public class Box<T> {
private T item;
public void setItem(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
// Usage
Box<Integer> intBox = new Box<>();
intBox.setItem(123);
System.out.println(intBox.getItem()); // Output: 123
Collections
The Java Collections Framework (JCF) provides data structures like lists, sets, maps, and queues.
Collections often use generics to enforce type safety.
Common Collection Types:
1. List: Ordered, allows duplicates (e.g., `ArrayList`, `LinkedList`).
2. Set: No duplicates (e.g., `HashSet`, `TreeSet`).
3. Map: Key-value pairs (e.g., `HashMap`, `TreeMap`).
Example: Using Collections with Generics
java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/17
GUIs (Graphical User Interfaces)
Graphical programming in Java typically involves Swing or JavaFX for desktop applications.
Swing
A part of Java's standard library for building GUI applications.
Based on the Model-View-Controller (MVC) pattern.
Example: Simple Swing Application
java
import javax.swing.*;
public class SwingExample {
public static void main(String[] args) {
// Create Frame
JFrame frame = new JFrame("Swing Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
// Add Button
JButton button = new JButton("Click Me");
button.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Hello, Swin
g!"));
frame.add(button);
// Show Frame
frame.setVisible(true);
}
}
Scale for Graphical Programming
Scala is a language often used with functional programming but can also support GUI
development.
Scala-based GUI programming leverages Java libraries like Swing.
Example: GUI with Scala Swing
scala
import scala.swing._
object ScalaSwingExample extends SimpleSwingApplication {
def top: Frame = new MainFrame {
title = "Scala Swing Example"
contents = new Button {
text = "Click Me"
reactions += {
case event.ButtonClicked(_) => Dialog.showMessage(contents.head, "Hello, Scala Swin
g!")
}
}
}
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/17