Object Oriented Programming

Workshop 5

Workshop 5

Table of Contents

Inheritance

Abstract Classes

public abstract class Shape {
  // ...
  public abstract double getArea();  // every child must override getArea()
}
  1. If you label a class or method as abstract, what does it do?
    • class cannot be instantiated
    • indicates implementation is not complete
  2. What is the conceptual meaning of abstract classes?
    • useful generalisation that is not attached to a real-world entity
  3. How can we decide whether a class should be abstract or concrete?
    • does the class represent a real-world entity?
    • do the methods of the class make meaningful actions, or are they only being defined as a placeholder to be properly implemented by child class?
    • is the logic of the class incomplete?

Polymorphism

  1. Define polymorphism.
    • objects/methods may have different meaning in different contexts
    • literally “many forms”
    • ability to use objects/methods in many ways
  2. In what ways does Java allow polymorphism?
    • overloading: same method with various forms depending on signature
      • classic example: println
    • overriding: same method with various forms depending on class
    • substitution: using subclasses in place of superclasses
    • generics: class parametrised by type
  3. What is upcasting, and why is it useful to be able to write code like: Piece[] pieces = new Piece[]{new Rook(), new King(), new Queen()}
    • upcasting is the process of assigning a reference to a subclass to a variable of parent-class type
    • this allows you to refer to a generic parent class, without needing to know which child class it is in advance, making code much more general
  4. What is downcasting? What do you need to be aware of when using it?
    • downcasting is casting a reference from a parent class to a child class
    • this will only work if the original object is actually of child class type

Edit this page.