1/89
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai |
|---|
No analytics yet
Send a link to your students to track their progress
Abstract Data Types (ADT)
Data and operations on data that are precisely specified independent of any implementation
Data and operations on data types without needing to know how they are implemented
An _____ specifies what data is stored and what operations can be done, but not how it is stored in memory.
We can change implementation, but interface will remain the same
Data Structure
A systematic approach to storing and accessing data so that it can be used for a specific purpose
A __________ is implementation of an ADT (i.e., if an ADT is an interface, a _________ is a class that implements the interface)
Benefit of programming to ADT
code depends on behaviour (“add”, “contains”) not implementation (“HashSet” vs “TreeSet”).
It lets you write code against Set (the ADT/interface) so you can change the implementation later (e.g., HashSet → TreeSet) without changing client code.
It reduces dependency on one concrete class and makes the program easier to maintain/change
Interface
Defines what a component can do (a contract or a blueprint)
An interface defines method signatures without implementation, allowing classes to implement these methods as needed. Interfaces provide a common structure for classes and enable polymorphism by allowing objects to be treated as instances of the interface
An interface doesn't give you any "DNA" or working code. It just gives you a "To-Do list." Any class that signs the contract must write its own code for those tasks.
Relationship: "Acts-like" or "Can-do" (A Phone can-do Telecommunication).
No Logic: It’s an empty shell. It just says, "You must have a connect() method, but I don't care how you write it."
Flexibility: A class can implement many interfaces. A SmartPhone can implement Camera, GPS, and Phone all at once
Implementation
Defines how it is done (code and logic)
Modularity
Means breaking your program into separate, independent pieces that do one job each.
With ADTs in Java:
The interface (what the ADT can do, like push or pop for a stack) is one module.
The implementation (how it actually works, like using an array or linked list) is another module.
Why Modularity is helpful
Why this helps:
You can change the implementation without touching the code that uses it.
Each piece can be tested and understood separately.
It makes the program cleaner and easier to maintain.
Tight Coupling
A situation in programming where one class or module is highly dependent on the details of another. This means changes in one part of the code are likely to require changes in the other, making the system less flexible and harder to maintain.
Polymorphism Cons
The list cannot directly access SavingsAccount-specific methods.
You cannot call addInterest() through an Account reference.
Downcasting would be required to use SavingsAccount-specific methods. This can lead to unsafe casts.
Makes special behaviour harder to use.
Why we can’t access subclass-specific methods if we use polymorphism
The Compiler checks the reference type (Account), not the object type (SavingsAccount). If the method isn't defined in the Account class, the code won't compile.
Explicit Downcasting
To access those methods, you must use __________. This is "unsafe" because if the list contains a ChequingAccount and you try to cast it to a SavingsAccount, the program will crash with a ClassCastException.
Why Programming to ADT is Useful
code depends on behaviour (“add”, “contains”) not implementation (“HashSet” vs “TreeSet”).
It lets you write code against Set (the ADT/interface) so you can change the implementation later (e.g., HashSet → TreeSet) without changing client code.
It reduces dependency on one concrete class and makes the program easier to maintain/change
Code Segment
Program instructions of the program itself
Static Area
Data of class variables, class definitions, etc.
Heap
Dynamically allocated memory (most objects live here)
Free Space
Unused memory that is available for the heap or stack
Stack Memory
Function call stack (used whenever a method is called)
Used to store local variables
Used up each time you call a method or run code within a black of code
Static Modifier
Indicates that a variable or method belongs to the class itself rather than instances of the class. A static variable is shared among all instances of a class and can be accessed without creating an instance.
Non-static Modifiers
Unique to each instance of the class and can only be accessed through an object of that class
Method Overloading
Methods in the same class have the same name but use different parameter lists
Having multiple methods with the same name but different parameters.
Method Overriding
Methods in different classes
A subclass providing a specific implementation of a method already defined in its parent class.
How does Java search for a method when it is called by a class?
The class of the object making the call.
It's superclass.
The interfaces that the class implements.
The superclasses of the superclass, and so on, up the class hierarchy.
Modular
Made of several parts that can be put together in different ways
Interface Class
A specification (i.e., a list) of a set of methods such that any classes implementing the interface are forced to write these methods
All methods in an _______ must be declared with public
Does not belong to any particular class
Classes can implement more than one _______, in any order, separated by a coma
_______ can extend other _______
_______ can ensure that these objects have specific methods defined
Abstraction
A technique for arranging complexity of computer systems; it works by establishing a level of complexity on which a person interacts with the system, suppressing the more complex details below the current level
Functions/procedures/methods are another form of _____________ (classes too!)
Lets us use objects without fully knowing how they work
the process of reducing complex, concrete information into essential, manageable concepts by filtering out irrelevant details.
Object-Oriented Code
easier to understand (relates to real world objects)
better organized and hence easier to work with
simpler and smaller in size
more modular (made up of plug-n’-play re-usable pieces)
better quality
high productivity and a shorter delivery cycle
less mainpower required
reduced costs for maintenance
more reliable and robust software
pluggable systems (updated UI’s, less legacy code)
Legacy Code
Source code inherited from someone else or an older version of software that remains in use but is difficult to maintain, update, or test. It is often characterized by lack of automated tests, outdated technology, and high risk when making changes.
Encapsulation
__________ allows us to hide internal details; other classes are forced to interact with our classes using the public methods available
leads us to code that is easier to maintain and more robust
________ is hiding unnecessary details of a code
Principles of OOP
Abstraction
Encapsulation
Inheritance
Polymorphism
Class
the design of a type of object, specifying what state and behaviour the class has (a template)
defines structure and behaviour
Each _____ that we define represents a new type (or category) of object
Attributes represent the differences between members of a _____
The “cookie cutter”
Object
represents multiple pieces of information that are pieced together
A bundle of data and associated behaviours (i.e. methods) that can be applied to that data
a specific ‘physical’ copy of a specific class/type
Specific usable entity that follows that structure and behaviour
_________ = state + behaviour
All ______ of a class have common attributes because they are entities of a class
Constructor
A _________ initialises an object when it is created. It sets the initial state of an object by assigning values to its attributes.
_______ can also enforce certain rules, such as ensuring that required fields are provided upon object creation.
Polymorphism
The computer knows they are actually different types and executes the specific code for each.
Shows up in two ways: Method overriding, method overloading
ex. We can ask all Person objects what their name is. This is independent as to whether or not they are instances of Employees, Managers, Customers, etc.
We can deposit to any BankAccount, independent of its type
Type-casting allows us to treat objects more GENERALLY
Our code becomes easier to understand
more intuitive and
quicker to write since the program does not need to remember as many methods
Occurs when we have many classes that are related to each other by inheritance.
Private vs Protected vs Public
Private variables and methods are accessible only within the class
Protected variables and methods are accessible within the class and its subclasses
public variables and methods are accessible everywhere, including subclasses and other classes
Abstract Class
_______ cannot be instantiated. They can have abstract methods, and the inheriting classes must implement these methods if they can be instantiated.
Abstract vs. Interface
Will often have non-abstract methods with complete code
vs
Cannot declare any attributes nor static constants in an interface
In old versions of JAVA, we could only declare “empty” methods in an ______ (newer versions can supply code for them)
All methods in an ______ must be declared with public
Typecasting
An object can be cast to:
Its own class
Any superclass
Any interface it implements (directly or through inheritance)
Downcasting
Superclass → Subclass (explicit cast required)
casting an object to a sibling (fellow) subclass of the same superclass will cause a ClassCastException at runtime.
may be required to use subclass-specific methods in polymorphism
Upcasting
Subclass → Superclass (automatic)
Advantages of OOP
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
OOP makes it possible to create full reusable applications with less code and shorter development time
How Memory Grows and Shrinks Over Time:
Each time a method is called or local variables are declared, stack space is used up
When method returns, stack space is used up
Each time a constructor is called to make an object, heap space is freed up
Heap space is freed up again by the garbage collector, every once in a while
Set
An abstract data type that does not allow duplicate elements to be added
Generally unordered
Particular location of an element may change according to the particular set implementation
Operations work similar to that of Lists with the except that the elements are not necessarily maintained in the order they were added in
Stack ADT
An abstract data type that stores elements in a last-in-first-out (LIFO) order. Elements are added and removed to/from the top only
Undo operations
Dictionary/Map
An abstract data type that stores a collection of unique keys and their associated values. Each key is associated with a single value.
List
An abstract data type that implements an ordered collection of values, where the same value may occur more than one
Use a general ____ whenever we have elements coming in and being removed in a random order
Example to use List
When we have a shelf of library books, we may need to remove a book from anywhere on the shelf and we may insert books back into their proper location when they are returned
Elements in a general list are stored in particular positions in the list
accessible according to their index position in the list
Specific Implementation vs ADT
Flexibility / Decoupling
You can change the implementation without affecting client code.
Example: Switching from ArrayStack to LinkedStack is seamless if you code to Stack interface.
Maintainability
Code depends on behavior rather than internal details.
Easier to read, test, and debug.
Interchangeability
Multiple implementations of the same ADT can be swapped for performance, memory, or concurrency reasons without rewriting code.
Abstraction / Encapsulation
Hides implementation details.
Prevents clients from misusing internal structure.
Queue
An abstract data type that stores elements in a first-in-first-out order. Elements are added at one end and removed from the other
People get served from the front of the line first; when people arrive, they go to the back
Deque
An abstract data type that is analogous to a double-ended queue. Elements are added/removed to/from either end.
Allows us to add/remove from the front or the back of the queue at any time, but modifications of the middle are NOT allowed
Similar to a regular single-ended queue, but it is a little more flexible in that it allows removal from the back of the queue and insertion at the front
Example of when we might use deque is when we implement “Undo” operations in a piece of software
we add it to the front of the queue when we do an operation, then when we undo, we remove it from the front of the queue
Client Code
______ is any code that uses or calls a specific class, method, or library.
The Relationship: If Class A calls a method in Class B, Class A is the client.
The Analogy: If a Class is a vending machine, the ______ is the customer pressing the buttons.
The Goal: Good design means the client shouldn't have to know how the class works inside; it should just "tell" the class what to do.
Encapsulation (The "Black Box")
_____________ is about bundling data and methods together and hiding the internal state of an object from the outside world.
The Idea: You use "private" variables so other parts of the program can't accidentally mess with an object's internal data.
Real-world Example: A Thermostat. You can turn the dial to change the temperature (the public interface), but you can't reach inside and manually wiggle the wires or the sensor (the private data).
Benefit: It prevents "spaghetti code" where one change breaks ten other unrelated things.
Abstraction (The "User Manual")
_____________ is about hiding complexity and only showing the essential features. It’s very closely related to the ADT concept we discussed earlier.
The Idea: You create a simple interface for a complex process.
Real-world Example: A Coffee Machine. You press a "Brew" button. You don't need to know the water pressure, the exact temperature of the heating element, or the timing of the grind. You just want the coffee.
Benefit: It allows you to use complex tools without needing to be an expert on their inner workings.
Inheritance (The "Family Tree")
_____________ allows one class to derive its attributes and behaviors from another class. It promotes code reuse.
The Idea: You create a "Parent" (Superclass) and a "Child" (Subclass). The child gets everything the parent has but can add its own unique "flair."
Real-world Example: * Parent: Bird (has feathers, lays eggs).
Child: Penguin (inherits feathers/eggs, but adds "swims") and Eagle (inherits feathers/eggs, but adds "flies high").
Benefit: You don't have to rewrite the "lays eggs" code for every single bird species.
Polymorphism (The "Shape-Shifter")
_____________ (meaning "many shapes") allows different objects to be treated as instances of the same general class, but each responds to the same command in its own way.
The Idea: One method name, many different implementations.
Real-world Example: A speak() command.
If you tell a Dog to speak(), it says "Woof!"
If you tell a Cat to speak(), it says "Meow!"
The command is the same, but the result depends on who is listening.
Benefit: You can write a single piece of code that works with many different types of objects simultaneously.
Reference versus Object
Product p1 = new Product("Laptop");
new Product("Laptop"): This creates the Object. The computer carves out space on the Heap to store the string "Laptop" and any other product data.
p1: This is the Reference. It is a variable named p1 that stores the address of that new space on the Heap.
=: This "points" the remote at the TV
Product p1 = new Product("Laptop");
Product p2 = p1; // p2 now points to the same object as p1
If you change the price using p2.setPrice(500), and then check p1.getPrice(), it will also be 500. There is only one "Laptop" object; you just have two remotes for it.
Composition
Describes a “has-a” relationship
Create complex objects by combining simpler, independent objects together. Instead of a class inheriting behaviour from a parent, it contains instances of other classes to handle specific tasks.
A Car has an Engine, has Wheels, and has a Transmission.
Where does the reference live?
The Stack
Where does the object live?
The heap
Reference Definition
A variable that holds the memory address (the "link") to an object.
Loose Coupling
__________ means classes are minimally dependent on each other and communicate through interfaces or abstractions instead of concrete implementations.
Key Word: Independence
Tight Coupling
__________ occurs when two classes are strongly dependent on each other. If one class knows the internal details of another class, any change in one class will directly affect the other.
Client Code
_______ is simply any code that uses a specific class, method, or library. It is the "customer" of the API.
The Relationship: If you write a class called Bank and I write a class called ATM that uses Bank.getBalance(), my ATM class is the ________.
Controller
Acts as the middleman. It listens for user input (clicks, typing) and tells the Model to update accordingly.
Public API (Application Programming Interface)
The ________ is the set of "visible" tools a class or library gives to the outside world. It is the interface that tells other programmers: "Here is what you are allowed to do with me."
What it includes: Public methods, public variables, and constructors.
The "Black Box" Analogy: Imagine a microwave. The buttons on the front (Start, Timer, Power Level) are the _________. You can use them to interact with the machine without needing to understand the high-voltage transformer inside
Why a vehicle class shouldn’t implement insurable interfaces
If you make the parent Vehicle implement Insurable and Sellable, then every vehicle (Bicycles, Scooters, Tanks) is forced to be insurable and sellable.
Java allows a class to extend one class but implement many interfaces. By having Car extends Vehicle implements Insurable, Sellable, you are saying a Car is a Vehicle, but it also has these specific "contractual" abilities that other vehicles might not have.
Many of the Java Collections classes support automatic sorting using the Comparable interface. The fact that pre-written sorting code can be applied to any class that implements the Comparable interface is most closely related to which principle of OOP?
Polymorphism
Model
Handles data and logic (domain operations)
View
Displays information to the user.
When is a downcast most justifiable in well-designed code?
When there is strong guarantee from the design or local logic about the runtime object’s more specific type, and the code truly needs subtype-specific behaviour.
What types of fields of a superclass are accessible to a subclass?
Protected
Public
Default
NOT private.
Runtime Polymorphism
Is the ability of an object-oriented system to decide which implementation of a method to execute at the moment the code runs, rather than when it is compiled.
done through METHOD OVERRIDING done at RUNTIME
How do TreeSets sort?
Uses compareTo() (from the Comparable interface) or a Comparator. If compare(a, b) == 0, the TreeSet considers them duplicates
Collections that use .equals()
The most common sets use the .equals() method to determine if an object is a duplicate. However, for performance reasons, they almost always use .hashCode() first to narrow down the search.
HashSet
LinkedHashSet
ArrayList / LinkedList (via contains()): While Lists allow duplicates, if you call the contains(Object o) or remove(Object o)methods, they iterate through the list and use .equals() to find a match.
How does runtime polymorphism work?
The magic of __________ happens when you have a Parent Class reference pointing to a Child Class object.
At Compile Time: The compiler checks the Reference Type to see if the method exists. If the parent class has the method, the code compiles.
At Runtime: The Java Virtual Machine (JVM) looks at the actual Object Type in memory and executes the version of the method defined in that specific subclass.
Character myHero = new Warrior(); // Reference is Character, Object is Warrior
myHero.attack(); // Output: "Swings a heavy sword!"
Even though myHero is labeled as a Character, the JVM "sees" it is actually a Warrior at runtime and chooses the sword attack.
LinkedList
A dynamic data structure where each element is a separate object, called a "node," containing both data and a reference to the next (and previous) node in the sequence
LinkedList versus Array
Arrays: When you delete or insert an element in the middle of an array, every subsequent element must be shifted over to fill the gap or make room, which is O(n).
Linked Lists: You only need to update the "pointers" or references of the neighboring nodes.
Why B is wrong: Linked Lists actually often use more memory because each node must store the data plus the reference to the next node (overhead).
Overriding versus Overloading
Overriding: Occurs in a subclass. You use the exact same signature (name and parameters) as the parent class to provide a specific implementation.
Overloading: Occurs when you have multiple methods with the same name but different parameter lists (different types or number of arguments) within the same class (or across a hierarchy).
Dynamic Dispatch
A mechanism in Java where the call to an overridden method is resolved at runtime rather than at compile time. This is the core engine behind runtime polymorphism
Java resolves method calls based on the actual object type at runtime, not the reference type.
Example of Method Overloading
Java
public class Calculator {
// Version 1: Two integers
public int add(int a, int b) {
return a + b;
}
// Overloaded Version: Three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded Version: Different types (doubles)
public double add(double a, double b) {
return a + b;
}
}
Example of Method Overriding
Java
public class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
public class Dog extends Animal {
@Override // This annotation is optional but recommended
public void makeSound() {
System.out.println("Bark!");
}
}
final keyword when referring to an object
In Java, when you declare an object reference as final, you are locking the reference (the "pointer"), not the object itself.
What stays the same: You cannot reassign the variable to a new object (e.g., myFinalList = new ArrayList(); would fail if it was already assigned).
What can change: You can still modify the internal state of that object (e.g., myFinalList.add("Item"); works perfectly fine).
Catch block ordering
Ordered from most specific to general.
Propagation
In the context of programming and exception handling (like in the Java practice questions you were just working on), _______ is the process by which an error "travels" up the call stack until it finds a handler.
Think of it like a hot potato: if a method encounters a problem it doesn't know how to fix, it "throws" the error to the method that called it.

Method signature
Includes name and parameters (order and type)
Comparable compareTo()
In Java's Comparable interface, the compareTo method generally follows these rules to determine order:
Negative result: this comes before other.
Zero result: this and other are equal.
Positive result: this comes after other
ex.
If we want highest to lowest, Account A should come first.
Using other.balance - this.balance: 100−500=−400.
Since the result is negative, Account A (this) is placed before Account B, which is exactly what we want for a descending sort.