Back to Explore

OOP (Java) — Weeks 3–5: Relationships, Inheritance, Polymorphism, Abstraction (Concise Notes) Summary & Study Notes

These study notes provide a concise summary of OOP (Java) — Weeks 3–5: Relationships, Inheritance, Polymorphism, Abstraction (Concise Notes), covering key concepts, definitions, and examples to help you review quickly and study effectively.

1.8k words2 views
Notes

🔗 Relationships (Association, Aggregation, Composition)

Association

  • Association: a general relationship describing activity between two classes. Denoted by a straight line arrow and direction. A link is required for communication between classes.

Aggregation

  • Aggregation: an object owns a collection of other objects (weak ownership). Examples: Professor has many Students, Hotel has many Suites, Truck has many Wheels. Represented in code as a data field in the aggregating class.

Example (aggregation representation): public class Student { private Name name; private Address address; ... } public class Address { ... }

  • Aggregating class: e.g., Student (contains Address field).

Composition

  • Composition: a stronger form of aggregation — dependent life cycles (child cannot exist separately from parent). Examples: Room has-a Door, Car has-a Wheel. Composition is a special case of aggregation with stronger ownership.

Diagram note from slides: Student — Name / Address with multiplicity (e.g., 1..3 for a component).

Key difference

  • Composition = strong association (child tied to parent). Aggregation = weak association (child can exist independently).

🧬 Inheritance (is-a)

  • Inheritance: subclass is a specialization of superclass; subclass can be treated as parent type. Examples: Motorcycle is-a Vehicle, Car is-a Vehicle.
  • Use extends keyword: class Subclass extends Superclass { ... }
  • Substitution principle: you can use a subclass object wherever a superclass object is expected.

Think-through questions (from slides):

  • Can every class be inherited? No — classes declared final cannot.
  • Can a class inherit from more than one class? (Slides ask; standard Java: no multiple class inheritance.)
  • Do you always need to call superclass constructor when instantiating subclass? The subclass constructor must chain to a superclass constructor (explicitly via super(...) or implicitly to no-arg).

⚖ Overload vs Override

  • Overload: same method name, different signature (compile-time). Constructors can be overloaded.
  • Override: same method name and signature in subclass replaces parent implementation (run-time polymorphism). Constructors cannot be overridden (not inherited).
  • this used for constructor chaining within same class; super used to call superclass constructor/methods.

🧾 Abstract Classes & Methods

  • Abstract class: declared with abstract; cannot be instantiated; serves as a template for subclasses.
  • Abstract method: has no body (semicolon only); forces subclasses to provide concrete implementation.

Example (slides): public abstract class ManyShapes { ... public abstract double getCircumference(); // no body }

Rules & notes:

  • If a class contains an abstract method, the class must be declared abstract.
  • An abstract class may contain no abstract methods (still allowed).
  • A concrete subclass must implement all inherited abstract methods or itself be abstract.
  • Constructors of abstract classes should usually be protected (good practice) because making them public would defeat the purpose of preventing direct instantiation; subclasses call them via super(... ).

Why define earnings() as abstract? (slide answer)

  • Because earnings cannot be calculated for a general Employee; different concrete employee types compute earnings differently — abstract enforces each subclass to implement it.

Consequences of incorrect declarations:

  • Trying to instantiate an abstract class → compilation error.
  • If a class declares an abstract method but is not declared abstract → compilation error.

🔒 Class Abstraction & Encapsulation

  • Abstraction: separate class implementation from use; expose only what users need to know. Implementation details are encapsulated and hidden.
  • Encapsulation is achieved via access modifiers (private/protected/public).

Access modifiers summary (from slides):

  • public: visible everywhere; public classes visible across packages; members inherited.
  • protected: visible inside package and to subclasses (including across packages via inheritance).
  • private: visible only within the declaring class; not inherited.
  • Default (no modifier): package-private (visible inside package).

Access table (as in slides): Modifier | Class | Package | Subclass | Global Public | Yes | Yes | Yes | Yes Protected| Yes | Yes | Yes | No None | Yes | Yes | No | No Private | Yes | No | No | No

📚 References (as per slide footer)

  • Liang D. Y. (2020). Introduction to Java Programming, Comprehensive Version, 11th Ed.
  • Deitel, Java How to Program

🧩 Polymorphism (Week #4)

Polymorphism — "many forms": the capability of a method to do different things based on the object it acts upon. Allows programming in the general rather than the specific.

Key ideas:

  • A variable of a supertype can refer to a subtype object.
  • The same message (method call) sent to different objects yields different behavior — the object does the right thing.

Example (Food/taste): public class Food { public void taste() { System.out.println("Food has taste"); } }

Subclasses override taste(): public class Rice extends Food { @Override public void taste(){ System.out.println("Rice is sweet"); } } public class Potatoes extends Food { @Override public void taste(){ System.out.println("Potatoes are sour"); } } public class Peppers extends Food { @Override public void taste(){ System.out.println("Peppers are spicy"); } }

  • The call foodRef.taste() executes the override corresponding to the actual object at runtime.

⚙ Why use polymorphism?

  • Makes design flexible and extensible; new classes can be added with minimal change to generic code.
  • Simplifies programming via single interfaces with multiple meanings.
  • Interfaces are powerful for unrelated classes to be processed polymorphically.

🔁 Types of Polymorphism in Java

  • Dynamic (Run-time): Method overriding (late binding). The method implementation chosen at runtime based on actual object type.
  • Static (Compile-time): Method overloading (early binding).

🔍 Method Overriding Rules

  • Argument list (types and order) must exactly match the overridden method.
  • Access modifier of overriding method cannot be more restrictive than overridden method.
  • private, static, and final methods cannot be overridden (static can be re-declared in a subclass but not overridden polymorphically).

Example override (from slides): class Human { public void dress(){ System.out.println("Human can wear dresses"); } } class Girl extends Human { public void dress(){ System.out.println("Girl can wear dresses"); } public static void main(String[] args) { Girl obj = new Girl(); obj.dress(); } } // Output: Girl can wear dresses

🔗 Binding (early vs late)

  • Binding links a method call to its body. Java defers non-static binding until runtime (dynamic/late binding).
  • Static binding: resolved at compile-time (static, private, final methods).
  • Dynamic binding: JVM searches class hierarchy at runtime for appropriate implementation (most specific class first).

Example (reference vs object): Shape obj2 = new Circle(); // obj2.draw() calls Circle.draw() at runtime (dynamic binding) if draw is instance method.

🧠 Method Matching vs Binding

  • Compiler finds a matching method signature (based on declared parameter types) at compile-time.
  • JVM dynamically binds the actual implementation at runtime based on the object type stored in the reference.

🎮 Examples & Tips from slides

  • Video game example: SpaceObject superclass with subclasses Martian, Venusian, SpaceShip, LaserBeam — screen manager calls draw() polymorphically; each subclass draws differently.
  • Polymorphism promotes extensibility — new object types plug in without changes to manager code.
  • Remember: all object references in Java are potentially polymorphic.

📚 References (as per slide footer)

  • Deitel, Java How to Program
  • JavaFoundations; Liang, Introduction to Java Programming

🧾 Inheritance (Week #3)

Inheritance: a class acquires properties (fields and methods) of another. The inheriting class is the subclass (child), the other is the superclass (parent).

  • Purpose: model objects with shared behavior and avoid redundancy.
  • Use extends: class Subclass extends Superclass { ... }

🚗 Substitution Principle & Hierarchies

  • Because a Car is a specialized Vehicle, a Car object can be used where a Vehicle is expected.
  • Inheritance hierarchies allow shared behavior for related types (e.g., Vehicles, Question types).

❓ Example: Question / ChoiceQuestion (slides)

Question class (key parts shown): public class Question { private String text; private String answer; public Question() { text = ""; answer = ""; } public void setText(String questionText) { text = questionText; } public void setAnswer(String correctResponse) { answer = correctResponse; } public void display() { System.out.println(text); } public boolean checkAnswer(String response) { return response.equals(answer); } }

ChoiceQuestion subclass extends Question and adds choices: import java.util.ArrayList; public class ChoiceQuestion extends Question { private ArrayList choices; public ChoiceQuestion() { choices = new ArrayList(); } public void addChoice(String choice, boolean correct) { choices.add(choice); if (correct) { String choiceString = "" + choices.size(); setAnswer(choiceString); // must call public setter } } @Override public void display() { super.display(); // display question text for (int i = 0; i < choices.size(); i++) { int choiceNumber = i + 1; System.out.println(choiceNumber + ": " + choices.get(i)); } } }

Example run (from slides): In which country was the inventor of Java born? 1: Australia 2: Canada 3: Denmark 4: UnitedStates Your answer: 2 true

Notes from slides:

  • ChoiceQuestion cannot access private fields of Question (e.g., text) directly; use public methods like setAnswer, setText, or super.display().
  • Common beginner error: duplicating superclass private fields in subclass (creates two separate fields; wrong).

🔼 Overriding & super

  • Use super.method(...) to call superclass method implementations (e.g., super.display()).
  • Use super.variable/super.method() to differentiate members when names clash.
  • When overriding a method and calling the superclass version is required (e.g., augmenting behavior), invoke super.

Pitfall example in slides: public double getSalary() { double baseSalary = getSalary(); // WRONG — recursive call return baseSalary + bonus; } // Correct: use super.getSalary() to invoke Employee's implementation.

⚙ Object (cosmic superclass)

  • Every class implicitly extends Object if no explicit extends is declared.
  • Useful Object methods to override: toString(), equals(Object), hashCode().

toString() example override: public String toString() { return "BankAccount[balance=" + balance + "]"; }

  • toString() is called when concatenating objects to strings: "box=" + box invokes box.toString().

equals(Object) example outline for Stamp class: public boolean equals(Object otherObject) { if (this == otherObject) return true; if (otherObject == null || getClass() != otherObject.getClass()) return false; Stamp other = (Stamp) otherObject; return color.equals(other.color) && value == other.value; }

🔁 instanceof & casting

  • You can store subclass references in superclass variables: Question q = new ChoiceQuestion();
  • To safely cast from a superclass reference to a subclass, test with instanceof before casting: if (obj instanceof Question) { Question q = (Question) obj; }
  • Common errors shown in slides: calling methods not present in declared type (compile error) or illegal casts (ClassCastException at runtime).

❗ Common Errors & Tips from slides

  • Do not replicate private instance variables from superclass in subclass; instead use superclass public/protected methods.
  • Overriding vs overloading: parameter types must match exactly to override; otherwise you accidentally overload.
  • Use super when you need to call a superclass method that has been overridden.

✅ Sample TIT answers (from slides)

  • Manager subclass from Employee (example): public class Manager extends Employee { private double bonus; // inherited instance variables: name, baseSalary, plus bonus @Override public double getSalary() { return super.getSalary() + bonus; } }
  • To add a star before manager name: public String getName() { return "*" + super.getName(); }

📚 References (as per slide footer)

  • Deitel, Java How to Program
  • Horstmann, Big Java

Sign up to read the full notes

It's free — no credit card required

Already have an account?

Create your own study notes

Turn your PDFs, lectures, and materials into summarized notes with AI. Study smarter, not harder.

Get Started Free
OOP (Java) — Weeks 3–5: Relationships, Inheritance, Polymorphism, Abstraction (Concise Notes) Study Notes | Cramberry