20-CS-4003-001 Organization of Programming Languages Fall 2016
Virtual functions

Lambda calculus, Type theory, Formal semantics, Program analysis

All lectures
Motivation - virtuals and polymorphism

Instructions for applets:

All applets have a JButton labeled 'Applet'. Click it.

    1.   vir1.java

    Demonstration of virtual functions. Given a hierarchy of classes and an object obj of one of those classes. Cast obj to some level of the hierachy. From there and starting at that point, look up the hierarchy for a method whose prototype matches the method of obj that is invoked. Otherwise look down the hierarchy until reaching the level at which obj was created.
    2.   vir2.java

    The method invoked is always in objs class, regardless of cast.
    3.   vir4.java

    The method f() is missing from two levels.
    4.   vir3.java

    Any future Person type can be handled without fear of the code breaking because there will always be a getRank and setRank method to call.

Class Person is defined as are several concrete subclasses of Person including Vagrant, Student, and Professor. These are intended to be placed into a Vector. Associated with each subclass are methods, declared as virtuals in Person, called setRank and getRank. These operate on data that is known to the subclasses but not the base class. When subclass objects are removed their data types are known only as Person. Since setRank and getRank are virtual, the correct method will always be invoked.

    5.   vir5.java

    An interface can substitute for the Person class. Then implementing classes need to keep their own state and need to implement all the specified methods.
    6.   vir6.java

    An abstract class can be used as well.