Course notes taken for CSCB07/CSC207 at UofT (Software Design).

Polymorphism, Abstract Classes, Interfaces, Liskov, Singleton.

Polymorphism

The concept is basically that you should have a general super class, and sub classes takes different shapes and forms of the super class.

A basic example would be:

class Cat extends Animal {
    public void talk() {
        System.out.println("meow");
    }
}

class Snake extends Animal {
    public void talk() {
        System.out.println("szzzz");
    }
}

class Animal {
    public void talk() {
        System.out.println("...");
    }
}

Advantages

Recap

Downcasting

Animal a = new Cat();
Cat c = (Cat)a;

Function Binding

Function binding maps a function call to function implementation. It decides when I do a.talk(), which function should be invoked.

Static Binding

This binds call during compile time.

Dynamic Binding

Runtime binding. This is used in polymorphism, and this is why it works.

Animal a = new Cat();
a.talk(); // This is binded to Cat.talk not Animal.talk during runtime.

Dynamic binding are used for all methods except:

final Keyword

If a method is final, it

If a class is final, it

Interfaces

A class can implement multiple interfaces but can only extend one class.

CLasses from different inheritance tree can implement the same interface.

Interfaces are used when different classes have their own “characteristics”, for example:

class ComputerScienceStudent extends Student implements AntiSocial, LovesPizza {

    public void beAwkward() {

    }

    public void eatPizza() {

    }

}

You can’t create a new interface instance, since nothing is implemented.

Abstract Classes

Abstract class is like the middleground of classes and interfaces, it can contain abstract methods that must be implemented.

public abstract class Student {
    public String getName() {
        return "haha";
    }

    abstract public void study();
}

You can’t create instance of abstract classes.

Singleton Pattern

Singleton is used when multiple other instances must share a single instance. For example, file system.

public class FS {
    public static FS ref = null;
    private FS(){}
    public static FS createInstance() {
        if(ref == null) ref = new FS();
        return ref;
    }
}

Liskov Substitution Principle

“If it looks like a duck, quacks like a duck, but needs batteries, you probably have the wrong abstraction”.

For any important properties of a type: