Assessment quick reference — Q1 & Q2
This file contains concise notes, examples and exam-style hints tailored to your assessment topics.
- Q1: Classes & Objects, Inheritance, Abstract Classes, Interfaces
- Q2: Exception Handling, File Handling, Collection Framework
Use these as quick revision notes when solving main.java files in this folder.
Q1 — Classes & Objects, Inheritance, Abstract Classes, Interfaces
Purpose: implement data models, reuse code via inheritance, express contracts with interfaces and reuse base behavior with abstract classes.
Key concepts
- Class: blueprint with fields and methods.
- Object: an instance of a class (created with
new). - Constructor: initializes an instance. If none provided, a default no-arg constructor exists.
this: refers to the current instance.static: member belongs to the class, not instance.
Minimal example — class and object:
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String toString() { return title + " by " + author; }
}
// usage
Book b = new Book("Java Basics", "A. Author");
System.out.println(b);Inheritance
extendsadds a parent class.- Use
super(...)to call parent constructors andsuper.method()to call parent implementations. - Prefer composition if "has-a" fits better than "is-a".
Example — inheritance and overriding:
public class Animal { public void speak() { System.out.println("..."); } }
public class Cat extends Animal { @Override public void speak() { System.out.println("Meow"); } }
Animal a = new Cat();
a.speak(); // prints "Meow"Abstract classes
- Use
abstract classwhen you want partial implementation and common fields/methods. - Can have abstract methods (no body) which subclasses must implement.
public abstract class Shape {
double x, y;
public Shape(double x, double y) { this.x = x; this.y = y; }
public abstract double area();
}Interfaces
- Declare a contract: methods that implementing classes must provide.
- Since Java 8, interfaces can have
defaultandstaticmethods. - A class can implement multiple interfaces.
public interface Printable { void print(); }
public class Report implements Printable { public void print() { System.out.println("report"); } }Common exam pitfalls (Q1)
- Forgetting to use
@Overridefor overridden methods —@Overridehelps catch signature mistakes. - Not providing
serialVersionUIDwhen serializing classes (if required by question context). - Confusing
staticwith instance members. - Using package-private unintentionally when classes are in different packages (visibility errors).
Short checklist for Q1 problems
- Identify entities (classes) and their relationships (extends/implements).
- Decide which methods should be abstract or default.
- Implement constructors and
toString()for easy printing inmain. - Keep methods small: single responsibility.
Q2 — Exception handling, File handling, Collection Framework
Exception handling
- Checked exceptions (e.g.,
IOException) must be declared (throws) or handled (try/catch). - Unchecked exceptions extend
RuntimeExceptionand are not required to be declared/handled. - Use try-with-resources for AutoCloseable resources (streams, readers, writers).
Example — try-with-resources:
try (BufferedReader br = new BufferedReader(new FileReader("in.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("IO error: " + e.getMessage());
}Best practices — exceptions
- Catch specific exceptions, not
Exception, unless the problem needs a catch-all. - Use
finallyonly if needed (resources should be closed in try-with-resources). - For library code, prefer throwing meaningful exceptions (wrap low-level exceptions with contextual messages).
File handling
- Text files:
BufferedReader/BufferedWriterorFiles(NIO) for small files. - Binary files / object storage:
ObjectOutputStream/ObjectInputStreamand implementSerializable. - Use
Paths/Filesfor concise operations in modern code.
Examples
Read all lines (NIO):
List<String> lines = Files.readAllLines(Paths.get("data.txt"));Serialize objects:
public class Item implements Serializable { private static final long serialVersionUID = 1L; String name; }
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("items.ser"))) {
oos.writeObject(itemsList);
}Collection framework — quick cheats
- List (ordered, may contain duplicates):
ArrayList,LinkedList. - Set (unique elements):
HashSet,LinkedHashSet,TreeSet(sorted). - Map (key -> value):
HashMap,LinkedHashMap,TreeMap.
Typical operations
List<String> l = new ArrayList<>();
l.add("a");
Collections.sort(l); // sort
Map<String,Integer> freq = new HashMap<>();
freq.put(key, freq.getOrDefault(key, 0) + 1);
Set<Integer> s = new HashSet<>();
s.add(5);Exam tips — collections
- Use
HashMapfor frequency counters. - If ordering matters, choose
LinkedHashMaporTreeMapaccordingly. - For deduplication while preserving order: use
LinkedHashSetor stream operations. - Remember
List.get(index)is O(1) forArrayList, but O(n) forLinkedList.
Common Q2 pitfalls
- Not closing streams (use try-with-resources).
- Confusing
IOExceptionandFileNotFoundExceptionhandling —FileNotFoundExceptionis a subclass ofIOException. - Using equality
==for strings — useequals()orequalsIgnoreCase(). - When deserializing, class definition changes can cause
InvalidClassException(serialVersionUID mismatch).
Quick exam practice problems & approach
- Q1-style: "Design a
Vehiclehierarchy withCarandBike; makeVehicleabstract with an abstractfuelEfficiency()method. Provide constructors andtoString()methods."
Approach:
- Create
abstract class Vehiclewith fields common to all. - Implement
CarandBikewith overrides forfuelEfficiency(). - Instantiate in
mainand print.
- Q2-style: "Read names from
students.txtand print counts per letter using a Map; handle missing file gracefully."
Approach:
- Use
Files.readAllLinesorBufferedReaderinside try-with-resources. - Use a
Map<Character,Integer>frequency map. - Catch
IOExceptionand print a user-friendly message.
Compile & run reminders (PowerShell)
javac path\to\Main.java
java -cp path\to MainWhen packages are used, run with the fully-qualified class name from project root.
If you want, I can:
- generate skeleton
.javafiles for the two sample problems above (complete and ready-to-run), or - annotate a specific
main.javain yourAssessmentsfolder for feedback.
File created: ASSESSMENT_Q1_Q2.md — next step: tell me if you want skeleton code or annotated files for particular assignments.