130 likes | 207 Views
Virtual Types. by Kresten Krab Thorup & by Mads Torgersen. Outline. OO Type System Limitation Examples Type safety MyType, ThisType, @T. OO Type System Limitation. Methods can be virtual But not inner classes No change to parameter when overriding Or only covariant
E N D
Virtual Types by Kresten Krab Thorup& by Mads Torgersen
Outline • OO Type System Limitation • Examples • Type safety • MyType, ThisType, @T
OO Type System Limitation • Methods can be virtual • But not inner classes • No change to parameter when overriding • Or only covariant • No change to the type of instance variable
Example (Orig. OO) • interface Observer{ void notify(Subject s, Object e);} • class Subject{ Observer [] observers; void notifyObservers(Object e){ foreach(Observer ob : observers) ob.notify(this, e);}
Discussion (Orig. OO) • Specialize subject? • Specialize event? • Runtime type-casting
Example (VirtualTypes, Observer) • Interface Observer{ typedef SType as Subject; typedef EventType as Object; void notify(SType s, EventType e);}
Example (VirtualTypes, Subject) • class Subject{ typedef OType as Observer; typedef EventType as Object; OType [] observers; notifyObservers(EventType e){ foreach(OType ob : observers) ob.notify(this, e);}
Example (VirtualTypes, Specialize) • interface WindowObserver extends Observer{ typedef SType as WindowSubject; typedef EventType as WindowEvent;} • Class WindowSubject extends Subject{ typedef OType as WindowObserver; typedef EventType as WindowEvent;…}
Discussion (VirtualTypes) • Strongly typed, specialized subject and event • But parameter type narrowing! • class Subject: notifyObservers(EventType e) -> notifyObservers(Object e) • class WindowSubject:-> notifyObservers(WindowEvent e) • Subject subj = new WindowSubject();subj.notifyObserver(new Object());// Error!!
Type Safety • Problematic statements: • Subject subj = new WindowSubject();subj.notifyObserver(new Object()); • Correction: • Subj.notifyObserver( new subj.EventType())
Type Safety (cont.) • τi should be a subtype of the virtual type variable Ti in τ’ instead of the concrete type assigned to Ti. • <τ’, Ti> v.s. τ’.Ti • subj.EventType v.s. Object
@T • “Exact type” • class B extends A{} • A a = new B(); • @A aExact = new A(); • @A aExact = new B(); // Error • A a = new B();@A aExact = a; // Error • @A aExact = (@A) a; // Runtime check
ThisType • interface ListIfc{ public char head(); public @ThisType tail(); public void setHead(char h); public void setTail(@ThisType t);} • class List implements @ListIfc{ protected char h; protected @ThisType t;…}