Transcript
Page 1: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 130© A. Poetzsch-Heffter, TU Kaiserslautern

5. Subtyping and InheritanceOverview:

• Core concepts

• Subtyping and dynamic binding

• Inheritance

• Object-oriented type systems

• Behavioral subtyping

Remark:

5.1 Core Concepts

Object-orientation has three core concepts :

1. Object model

2. Object interfaces

3. „is-a“ relation between objects enabling

- polymorphism and classification

- abstraction and specialization

Notice that the object model is a prerequisite toobject interfaces which in turn are the basis for t he„is-a“ relation.

Page 2: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 131© A. Poetzsch-Heffter, TU Kaiserslautern

We can say that an object/item/term of type A isalso an object/item/term of type B iff A-objects have all relevant properties of B-objects.

„is-a“ relations can be used to classify objects/items/terms into hierarchical structures according to the irproperties. The result is often called a classifica tion.

The objects/items/terms higher up in the classifica tionare called more general /abstract than those belowthem which in turn are more special /concrete thanthe former.

Explanation: („is-a“ relation, classification)

Example: (classification)1. Classification of vertebrates:

Vertebrate

Fish Amphibian Reptile BirdMammal

Whale ArtiodactylPrimate …

Page 3: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 132© A. Poetzsch-Heffter, TU Kaiserslautern

2. Classification of figures:

Figure

Ellipse Polygon

Circle TriangleQuadrangle

Parallelogram

RectangleLozenge

Square

Arrows representthe „is-a“ relation

Goal: Apply classification to software artefacts!

Page 4: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 133© A. Poetzsch-Heffter, TU Kaiserslautern

Classification in Object-Oriented Programming:

• Syntactic classification:

Subtype objects understand at least themessages that supertype objects understand andhave at least the same attributes ( wider interface).

• Semantic classification:

Subtype objects provide at least the behavior ofsupertype objects (behavioral subtyping).

• Substitution principle:

Subtype objects can be used where objects of theirsupertypes are expected.

Polymorphism is the quality of being able to assumedifferent forms.

A program part is polymorphic if it can be used for objects of different types.

Subtyping is a special kind of polymorphism in whichtypes are ordered w.r.t. inclusion relation: Object s ofa subtype belong as well to the supertype.

Explanation: (subtype polymorphism)

Page 5: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 134© A. Poetzsch-Heffter, TU Kaiserslautern

Other kinds of polymorphism:

– Parametric polymorphism (generic types)

– Ad-hoc polymorphism (method overloading)

Remark:

Abstraction means to form a general conceptby extracting common features from specific examples.

Explanation: (abstraction)

Designing Classifications:

Abstraction in OO-programming:

• Start from different objects or types with commonproperties

• Develop a more abstract type, extracting the common properties

• Corresponds to making the interface smaller

• Program parts that only rely on the common properties work for all objects of the more abstrac t type

Page 6: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 135© A. Poetzsch-Heffter, TU Kaiserslautern

Person

ProfessorStudent Bot

tom

-up

Example: (abstraction)

class Student {

String name;int regno;…

void print( ) {System.out.println(name);System.out.println(regno);

}}

class Professor {

String name;String room;…

void print( ) {System.out.println(name);System.out.println(room);

}}

interface Person {void print( );

}

class Student implements Person { … }

class Professor implements Person { …}

Abstraction

Page 7: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 136© A. Poetzsch-Heffter, TU Kaiserslautern

Person[ ] p = new Person[4];p[0] = new Student (…);p[1] = new Professor (…);

…for ( int i=0; i < 4; i++ )

p[ i ].print( );

Application of abstraction, that is, of type Person :

„Algorithm” based on Person

Specialization means to add specific properties to an object or to refine a concept by further charact e-ristics.

Explanation: (specialization)

Specialization in OO-programming:

• Start from general objects or types.

• Extend them and their implementations.

• Requirement: Behavior of specialized objects shoul d conform to behavior of more general objects.

• Program parts that work for the more general objec ts work as well for specialized objects.

• Implementation parts can be reused (inheritance).

Page 8: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 137© A. Poetzsch-Heffter, TU Kaiserslautern

Person

ProfessorStudent

Top-dow

n

Example: (specialization)

Specialization:

– Develop implementa-tion for type Person

– Specialize it

– Inheritance and over-riding can be used

class Person {String name;

…void print( ) {System.out.println( name );

}}

class Student extends Person {

int regno;…void print( ) {

super .print( );System.out.println(regno);

}}

class Professor extends Person {

String room;…

void print( ) {super .print( );System.out.println(room);

}}

Page 9: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 138© A. Poetzsch-Heffter, TU Kaiserslautern

5.2 Subtyping & Dynamic Binding

In a type system with subtyping , the types are partiallyordered. If S ≤ T, we say that S is a subtype of T and T a supertype of S.

Elements of the subtype belong as well to the supertype, i.e. types are not disjoint.

Explanation: (subtyping)

To enable classification of objects, all typed OO-languages support subtyping (there are as well other languages supporting subtyping).

Example: (type system with subtyping)

Types:

• primitive datatypes: int, char, byte, ....

• Interface types

• Class types

• Array types

Reference types

Page 10: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 139© A. Poetzsch-Heffter, TU Kaiserslautern

Subtype relation:

Declaration: interface S extends T1, T2, ... implicit: S <T1, S <T2, ...

Declaration: class S extends T implements T1, T2, ... implicit: S < T, S < T1, S < T2, ...

S < T implies: S[] < T[]

Subtype ordering is the reflexive and transitive clo sure.

• Syntactic interpretation of types: A type defines the attribute and method interface of its objects.

• Subtyping entails restrictions on method signature sin subtypes.

Remarks:

Typing Problem in OO-Languages:

To enable substitutability, a subtype object must ha ve

- all attributes of supertype objects;

- all methods of supertype objects.

Attributes and methods in the subtype must be compatible to those of the supertypes. Compatibilityconcerns typing and accessibility.

Page 11: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 140© A. Poetzsch-Heffter, TU Kaiserslautern

Let S be a subtype of T. Let TV be a type occurrence in T (attribute-, parameter-, result type) and SV thecorresponding occurrence in S. We say:

- SV and TV are covariant if SV is a subtype of TV.

- SV and TV are contravariant if TV is a subtype of SV.

Explanation: (Co-/contravariance)

OO-languages can only be statically typed iff:

- Attribute types are co- and contravariant, i.e. invariant.

- Parameter types are contravariant.

- Result types are covariant.

Fact:

Example: (Co-/contravariance)

interface C1 { String a; ... }

class D1 implements C1 { Object a; ... }

...

C1 cvar = new D1(); // initializes a

String svar = cvar.a;

// Type error: a not covariant in D1

1. Attributes have to be covariant:

Assuming that overriding of attributes is allowed:

Page 12: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 141© A. Poetzsch-Heffter, TU Kaiserslautern

interface C2 { Object a; ... }

class D2 implements C2 { String a; ... }

...

C2 cvar = new D2();

cvar.a = new Object();

// Type error: a not contravariant in D2

2. Attributes have to be contravariant:

3. Parameter types have to be contravariant:

interface C3 { int m(Object p); ... }

class D3 implements C3 {

int m(String s){ s.length();...}

}...

C3 cvar = new D3();

cvar.m( new Object() );

// Type error when executing m:

// parameter not contravariant

Page 13: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 142© A. Poetzsch-Heffter, TU Kaiserslautern

Covariance must as well hold for exception types.

interface C4 { String m(); ... }

class D4 implements C4 { Object m(){...} ...}

...

C4 cvar = new D4();

String svar = cvar.m();

// Type error: result type not covariant

4. Result types have to be covariant:

Remark:

• Co- and contravariance are important to understandobject-oriented typing and the principles underlyin gbehavioral subtyping.

• Java has a fairly inflexible type system:

- only restricted contravariance for parameters

- up to 1.4 no covariance for result types

Page 14: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 143© A. Poetzsch-Heffter, TU Kaiserslautern

Subtyping together with dynamic binding canexpress classification. Inheritance is not needed:

Every class hierarchy can be expressed by a hierachy of types where only the minimal typeshave an implementation.

Expressiveness of Subtyping:

Example: (refactoring class hierarchies)

A

B C

D

A

B C

D

AImpl

CImpl

DImpl

BImpl

Page 15: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 144© A. Poetzsch-Heffter, TU Kaiserslautern

5.3 Inheritance

Inheritance is a language concept to support theimplementation of subclasses. Subclasses are implemented by:

- inheriting all attributes, methods, and innerclasses from superclasses

- adding new members/features

- „adapting“ methods of superclasses

Inheritance guarantees that subclasses have at leas tthe features required by subtyping.

Techniques for adapting methods:

- Overriding: provide a new method declarationthat may use the overridden method (e.g. in Java)

- Specialization points: Methods contain namedstatement points at which subclasses can addcode (e.g. in BETA).

Page 16: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 145© A. Poetzsch-Heffter, TU Kaiserslautern

Example: (Inheritance)

class Person {String name;int gebdatum; /* Form JJJJMMTT */

void drucken() {

System.out.println("Name: "+ this.name);System.out.println("Gebdatum: "+gebdatum);

}

boolean hat_geburtstag ( int datum ) {return (gebdatum%10000)==(datum%10000);

}

Person( String n, int gd ) {name = n;geburtsdatum = gd;

}}

class Student extends Person {

int matrikelnr;int semester;

void drucken() {

super.drucken();System.out.println("Matnr: "+ matrikelnr);System.out.println("Semzahl: "+ semester);

}

Student(String n,int gd,int mnr,int sem) {super( n, gd );matrikelnr = mnr;semester = sem;

}}

Page 17: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 146© A. Poetzsch-Heffter, TU Kaiserslautern

The inheritance interface contains the features of class C that are potentially inherited by subclasse sof C.

Explanation: (Inheritance interface)

Problems of Inheritance:

- Subclasses may use the inherited code in a wrong way.

- The inheritance interface may be the interfacebetween two developers ( fragile baseclassproblem).

Example: (Breaking superclass invariants)

public class Superclass {protected int a, b, c;// invariant: a == b+c ;

}

public class Subclass extends Superclass {

public incrementC(){ c++; }}

Page 18: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 147© A. Poetzsch-Heffter, TU Kaiserslautern

Fragile Baseclass (FBC):

• Software, including reusable components, is often modified over time:

– Maintenance

– Bugfixing

– Reengineering

• Subclasses can be affected by changes to superclasses

How should we apply inheritance to make our coderobust against revisions of superclasses?

Develop Superclass

Implement Subclass

Modify Superclass

Development team 1 Development team 2

Page 19: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 148© A. Poetzsch-Heffter, TU Kaiserslautern

Example: (Fragile baseclass)

class CountingBag extends Bag {int size; // invariant: size==super.getSize();

int getSize( ) { return size; }

void insert( Object o )

{ super .insert( o ); size++; }}

class Bag {…int getSize( ) {

… // count elements}

void insert( Object o ) { … }

void insertAll( Object[ ] arr ) {for ( int i=0; i < arr.length; i++ )

insert( arr[ i ] );}

}

Page 20: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 149© A. Poetzsch-Heffter, TU Kaiserslautern

Object[ ] oa = … // 5 elements

CountingBag cb = new CountingBag( );

cb.insertAll( oa );

System.out.println( cb.getSize( ) );

Works well until implementation of insertAll ismodified, e.g. by inserting all array elementswithout using insert .

Hints to avoid FBC-problem:

- Override all methods that might break theinvariant in the subclass.

- In subclass implementation, only rely on the superclass specification, not on its implementation .

Page 21: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 150© A. Poetzsch-Heffter, TU Kaiserslautern

Inheritance and Delegation:

If attribute access is realized by getter andsetter methods, subclass implementation can be achieved by delegation:

- No inheritance

- Each object has a reference to superclass object

- Methods that are not declared locally are delegate dto superclass object.

Thus, the basic idea is:

class composition �

object composition

We first explain forwarding, an object composition technique weaker than delegation.

Forwarding means to resend messages that are notdirectly handled by the current object x to an obje ct ythat is referenced by x. Object y can be used to pr ovidethe functionality that is otherwise inherited by x.

Explanation: (forwarding)

x:B y:A

m(not in B)

Page 22: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 151© A. Poetzsch-Heffter, TU Kaiserslautern

If used methods and constructors in superclasses do not use methods that are overriden in subclassesand if objects only have private fields, then subcl asses can be implemented by forwarding instead ofinheritance.

Lemma: (forwarding transformation)

• Using forwarding is less powerful than inheritance .

• Checking the criterion of the lemma helps to detect error-prone inheritance situations (see example on next slide).

Remark:

Transformation of inheritance to forwarding:

• Introduce an interface type for each class.

• Classes implement corresponding interfaces.

• Subclasses do no longer inherit; they get an additional attribute for referencing an object of the former superclass.

• Constructors initialize reference to former super-class object.

• For inherited methods that are not overridden insubclasses a forwarding method is defined.

Page 23: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 152© A. Poetzsch-Heffter, TU Kaiserslautern

Example: (Usage of overridable methods)

class Oberklasse {String a;

Oberklasse(){a = "aha";m();

}void m(){

System.out.print("Laenge a:"+a.length());}

}

class Unterklasse extends Oberklasse {String b;

Unterklasse(){b = "boff";m();

}void m(){

System.out.print("Laenge b:"+b.length());}

}

class KonstruktorProblemTest {public static void main( String[] args ){

new Unterklasse();}

}

Page 24: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 153© A. Poetzsch-Heffter, TU Kaiserslautern

class A {private int i = 5;

A(){}

public int m( int ip ) {

return plusi(ip) + twice(ip);}public int plusi( int ip ) {

return ip + i;}private int twice( int ip ) {

return 2*i;}

}

class B extends A {private int i = 10;

B(){}

}

public class DelegForwInh {public static void main( String[] args ) {

A a = new B();

System.out.println(a.m(1));

}

}

Example: (Forwarding transformation)

Page 25: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 154© A. Poetzsch-Heffter, TU Kaiserslautern

interface AItf {int m( int ip ); int plusi( int ip );

}

class A implements AItf {private int i = 5;

A(){}

public int m( int ip ) {

return plusi(ip) + twice(ip);}public int plusi( int ip ) {

return ip + i;}private int twice( int ip ) {

return 2*i;} }

interface BItf extends AItf {}

class B implements BItf {private AItf inhPart;private int i = 10;

B(){ inhPart = new A(); }

public int m( int ip ){

return inhPart.m(ip);} public int plusi( int ip ) {

return inhPart.plusi(ip);}

}

Page 26: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 155© A. Poetzsch-Heffter, TU Kaiserslautern

class A { ... } // as above

class B extends A { ... } // as above

class C extends B {private int i = 20;

C(){}

public int plusi( int ip ) {

return ip + i;}

}

public class DelegForwInh {public static void main( String[] args ) {

A a = new B();

System.out.println(a.m(1));

a = new C();

System.out.println(a.m(1));}

}

The restrictions given in the Lemma are necessary:

If used methods are overridden in subclasses,forwarding does not work. Here is a subclass of Bthat overrides plusi used in m:

Transformation yields the following semanticallydifferent program:

Page 27: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 156© A. Poetzsch-Heffter, TU Kaiserslautern

interface AItf {int m( int ip ); int plusi( int ip );

}

class A implements AItf { ... } // as above

interface BItf extends AItf {}

class B implements BItf { ... } // as above

interface CItf extends BItf {}

class C implements CItf {private BItf inhPart;private int i = 20;

C(){ inhPart = new B(); }

public int m( int ip ){

return inhPart.m(ip);}public int plusi( int ip ) {

return ip + i;}

}

public class DelegForwInh1 { ...

a = new C();

System.out.println(a.m(1));}

Page 28: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 157© A. Poetzsch-Heffter, TU Kaiserslautern

To be able to use object composition instead ofinheritance, a message passing technique is neededthat is more powerful (and complex) than forwarding :

Method passing by delegation distinguishes threekinds of method invocations:

• statically bound invocations

• dynamically bound invocations

• delegating invocations

To handle delegating invocations, each invocationhas an additional implicit parameter orig for the original sender of the message. In dynamically boun d invocations orig is used instead of this .

Explanation: (delegation)

x:C y:B

(x,x).m(k) (y,x).m(k)

(x,x).plusi(k)

z:A

(z,x).m(k)

(z,x).twice(k)

Page 29: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 158© A. Poetzsch-Heffter, TU Kaiserslautern

Example: (delegating transformation)

We transform the above example using delegation.As Java does not support a second implicit paramete r,we make it explicit.

interface AItf {int m( AItf orig, int ip ); int plusi( AItf orig, int ip );

}

class A implements AItf {private int i = 5;

A(){}

public int m( AItf orig, int ip ) {return orig.plusi(orig,ip)

+ this.twice(orig,ip);}public int plusi( AItf orig, int ip ){

return ip + i;}private int twice( AItf orig, int ip ){

return 2*i;}

}

Page 30: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 159© A. Poetzsch-Heffter, TU Kaiserslautern

interface BItf extends AItf {}

class B implements BItf {private AItf inhPart;private int i = 10;

B(){ inhPart = new A(); }

public int m( AItf orig, int ip ){

return inhPart.m(orig,ip);} public int plusi( AItf orig, int ip ){

return inhPart.plusi(orig,ip);}

}

interface CItf extends BItf {}

class C implements CItf {private BItf inhPart;private int i = 20;

C(){ inhPart = new B(); }

public int m( AItf orig, int ip ){

return inhPart.m(orig,ip);}public int plusi( AItf orig, int ip ){

return ip + i;}

}

Page 31: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 160© A. Poetzsch-Heffter, TU Kaiserslautern

5.4 Object-Oriented Type Systems

To illustrate object-oriented typing, we consider asequential, tiny object-oriented Java subset ( StooJas).

We define:

- syntax and semantics of StooJas,

- the type system of StooJas,

- and show that the type system is sound.

public class DelegForwInh2 {public static void main( String[] s ){

AItf a = new B();System.out.println(a.m(a,1));a = new C();System.out.println(a.m(a,1));

}}

• The explicit formulation of delegation demonstrate sas well the often hidden complexity of inheritance.

• Delegation is a general design pattern with differ entapplications. Replacing inheritance by object compo -sition and delegation is certainly not the usualapplication.

Remark:

Page 32: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 161© A. Poetzsch-Heffter, TU Kaiserslautern

Syntax of StooJas:

Program = ClassDecl+ClassDecl = class ClassId [ extends ClassId ]

{ FieldDecl* MethodDecl* }FieldDecl = TypeId FieldId ;MethodDecl = TypeId MethodId (TypeId p) { Statement }TypeId = boolean | int | ClassIdStatement = { TypeId VarId; Statement }

| VarId = VarId . FieldId ;| VarId . FieldId = Exp ;| VarId = ( ClassId ) Exp ;| VarId = new ClassId( );| Statement Statement

| if( Exp ){ Statement }else{ Statement }| while( Exp ){ Statement }| VarId = VarId . MethodId( Exp );| VarId = super. ClassId@MethodId( Exp );

Exp = IntConst

| BoolConst

| null

| VarId

| UnOp Exp | Exp BinOp Exp

Page 33: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 162© A. Poetzsch-Heffter, TU Kaiserslautern

ClassId, FieldId, VarId are sets of identifiers whe reVarId contains this .

UnOp and BinOp are suitable operators yielding boolean- or int-values.

StooJas is an extension of StobJas. A StooJas-programcontains a special class Object .

Value = Bool| Int | null| ClassId ObjId

init : TypeId -> Value // initial value of a ty pe

The set of instance variables and methods:

InstVar = { <c,o,f> | f is a field of class c, o a n ObjId }

Method = { c@m | m is a method declared in class c }

Static semantics of StooJas:

Context Conditions of StooJas:

The context conditions of StooJas are those of Java .In addition, fields in subclasses must have an iden tifierdifferent from all inherited fields.

Page 34: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 163© A. Poetzsch-Heffter, TU Kaiserslautern

rtyp : Method -> TypeId // return type o f method

body : Method -> Statement // body of a method

_._ : Value x FieldId -> InstVar

v.f = if v = (c,o) and f is a valid field i n cthen <c,o,f>else undefined

Store and State are defined as for StobJas.

Furthermore, we define/assume:

Type = TypeId | NullT

≤ : Type x Type

S ≤ T ⇔ ( S is NullT and T is a ClassId )

or ( S and T are ClassIds and S is a subclass of T )

stype: Exp x StmtOcc � Type

// denotes the type of an expression in a statemen t

ftype: FieldId x ClassId � Type

ftype(f,C) = if f is a valid field in C then range type of f else undefined

Notice:

D is a subclass of C and f is a valid field in C==> ftype(f,D) = ftype(f,C)

Page 35: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 164© A. Poetzsch-Heffter, TU Kaiserslautern

vis: StmtOcc � Pow(VarId)

vis(STM) ⊆ VarId denotes the visible variables in STM

impl: MethodId x ClassId � Method

impl(m,C) = if m is valid method in C then B@m where B = C or

B is the nearest superclasswith a declaration for m

else undefinedNotice:

If impl(m,C) is defined and D is a subclass of C

then impl(m,D) is defined

Type conditions:

• Type of right-hand side of an assignment issubtype of type of left-hand side.

• Type of exp in a cast is supertype of cast type.

• Type of actual parameter expression is subtypeof formal parameter type of method.

• Expressions in conditions are of type boolean .

Page 36: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 165© A. Poetzsch-Heffter, TU Kaiserslautern

Definition: (well-typed state)

Let

• STM be a statement of a StooJas-program Π,

• SV: VarId � Value be a variable state, and

• OS: Store be an object store for Π.

SV is well-typed w.r.t. STM iff for all x in vis(STM):

type(SV(x)) ≤ stype(x,STM)

OS is well-typed iff for all <c,o,f> in InstVar:

type( read(OS,<c,o,f>) ) ≤ ftype(f,c)

A state S = (SV,OS) is well-typed w.r.t. STMiff SV is well-typed w.r.t. STM and OS is well-type d.

type : Value � Type

type( x ) = boolean if x is true or false

type( x ) = int if x is an integer

type( null ) = NullT

type( (C,o) ) = C

Page 37: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 166© A. Poetzsch-Heffter, TU Kaiserslautern

As for StobJas, we describe the semantics by apredicate (judgement) of the form

S : stmt � SQ

that expresses the fact that execution of stmtstarting in state S terminates in state SQ.

Dynamic semantics of StooJas:

Lemma: (well-typed expression evalutation)

If S is a well-typed state w.r.t. STM and e is a well-typed expression occurring in STM, then

type(S(e)) ≤ stype(e,STM)

Proof:

(as exercise)

Page 38: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 167© A. Poetzsch-Heffter, TU Kaiserslautern

Here are the rules for StooJas:

S(y) ≠ null

S: x=y.a; � S[ x:=read(S($),S(y).a) ]

S(x) ≠ null

S: x.a=e; � S[ $:=write(S($),S(x).a,S(e)) ]

type(S(e)) ≤ C

S: x=(C) e; � S[ x:=S(e) ]

true

S: x=new T(); � S[ x:=new(S($),T), $:=alloc(S($),T) ]

S: s1 � SQ , SQ: s2 � SR

S: s1 s2 � SR

S(e) = true , S: s1 � SQ

S: if(e){s1}else{s2} � SQ

S(e) = false , S:s2 � SQ

S: if(e){s1}else{s2} � SQ

Page 39: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 168© A. Poetzsch-Heffter, TU Kaiserslautern

S(e)=false

S: while(e){s} � S

S(e)=true, S:s � SQ, SQ:while(e){ s } � SR

S: while(e){s} � SR

S[v:=init(T)]: s � SQ

S: {T v; s} � SQ

S(y) ≠ null, MY = impl( type(S(y)), m),

S[this:=S(y),p:=S(e),res:=init(rtyp(MY))]:body(MY)� SQ

S: x = y.m( e ); � S[ x:=SQ(res), $:=SQ($) ]

S[p:=S(e),res:=init(rtyp(C@m))] : body(C@m) � SQ

S: x = super.C@m( e ); � S[ x:=SQ(res), $:=SQ($) ]

Remark:

• Every terminating execution that does not get stuc kcorresponds to a tree. The length of the execution isdefined to be the number of the tree nodes.

• The pre- and poststates of the nodes are called theintermediate states.

Page 40: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 169© A. Poetzsch-Heffter, TU Kaiserslautern

Theorem: (Type soundness of StooJas)

Let Π be a StooJas-program. The proof runs by induction on the execution length. STM denotes astatement in Π and S a well-typed state w.r.t. STM.

Induction base: Execution length is 1.There are four statement kinds to consider.

a) STM ≡ x=y.a; Well-typedness of S, S(y) ≠ null:

NullT < type(S(y)) ≤ stype(y,STM) ≤ Object� [[ y has to be of a reference type with field a ]]

S(y) = (d,o) for some d, o with d ≤ stype(y,STM)and a is a field of d, i.e. S(y).a is defined.� [[ S($) is well-typed ]]

...

If the execution of a statement STM in a program

- starts in a state that is well-typed w.r.t. STM an d

- terminates normally (that is, it does not get stuc k),

then all operations are defined and the intermediat e states and the resulting state are well-typed (w.r. t. the respective statements).

Proof:

Page 41: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 170© A. Poetzsch-Heffter, TU Kaiserslautern

b) STM ≡ x.a=e; Well-typedness of S, S(x) ≠ null:

NullT < type(S(x)) ≤ stype(x,STM) ≤ Object� [[ x has to be of a reference type with field a ]]

S(x) = (d,o) for some d, o with d ≤ stype(x,STM)and a is a field of d, i.e. S(x).a is defined. (*)

Well-typed expr. evaluation, typing conditions:

type(S(e)) ≤ stype(e,STM) ≤ ftype(a,stype(x,STM)) � [[(*), $ is only modified at S(x).a ]]

S[ $:=write(S($),S(x).a,S(e)) ] is well-typed

... � [[ S($) is well-typed ]]

type( read(S($),S(y).a) ) ≤ ftype(a,stype(y,STM)) � [[ type cond.: ftype(a,stype(y,STM))≤stype(x,STM) ]]

type( read(S($),S(y).a) ) ≤ stype(x,STM)� [[ well-typedness of S, only modified at x ]]

S[ x:=read(S($),S(y).a) ] is well-typed

Page 42: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 171© A. Poetzsch-Heffter, TU Kaiserslautern

c) STM ≡ x = (C)e;

Typing condition C ≤ stype(x,STM), type(S(e)) ≤ C:

type(S(e)) ≤ stype(x,STM) [[ well-typedness of S, only modified at x ]]

S[ x:= S(e) ] is well-typed

d) STM ≡ x = new T(); as above from typing condition T ≤ stype(x,STM).

Induction step: Execution length n+1.

Induction hypothesis: Theorem holds for executionswith length ≤ n .

We only consider method invocation. Super-calls are analogous, the other cases are trivial.

We show that:

a) if S(y)≠null, then MY=impl(type(S(y)),m) is defined.

b) S[this:=S(y),p:=S(e),res:=init(rtyp(MY))] is wel l-typed.

c) if SQ is well-typed, then S[ x:=SQ(res), $:=SQ($ ) ] is well-typed.

Page 43: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 172© A. Poetzsch-Heffter, TU Kaiserslautern

a) Well-typedness of S, S(y) ≠ null:

NullT < type(S(y)) ≤ stype(y,STM) ≤ Object

According to context conditions, class stype(y,STM) has a method m.

Thus type(S(y)) has a method m, and impl(type(S(y)),m) is defined.

b) S[this:=S(y),p:=S(e),res:=init(rtyp(MY))] is wel l-typed!

The context and type conditions, together with thewell-typed expression evaluation lemma yield:

type(S(y)) ≤ stype(y,STM) ≤ stype( this,body(MY))

type(S(e)) ≤ stype(e,STM) ≤ stype( p,body(MY))

Thus, induction hypothesis guarantees that SQ iswell-typed.

c) Well-typedness of SQ and type conditions yield:

type(SQ(res)) ≤ rtyp(MY) ≤ stype(x,STM)

Thus, S[ x:=SQ(res), $:=SQ($) ] is well-typed w.r.t .STM.

Page 44: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 173© A. Poetzsch-Heffter, TU Kaiserslautern

5.5 Behavioral Subtyping

Subtyping of programming languages enforces that

- no type errors occur, and

- there is a method implementation for each method invocation.

It does not guarantee that subtype objects behavelike supertype objects.

Example: (no specialization)

D-objects do not behave similar to C-objects:

class C {int a;int getA(){ return a; } void incr() { a++; }

}

class D extends C {int getA(){ return a+2; }void incr() {

throw new NullPointerException();}

}

Page 45: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 174© A. Poetzsch-Heffter, TU Kaiserslautern

Define the behavioral subtype relation based onspecified properties:

Each subtype object has to satisfy the specificationof the supertype.

For pre- and post-specifications this means:- pre[Supertype] => pre[Subtype]- post[Subtype] => post[Supertype]

Approach:

What does it mean that a subtype behaves like the supertype or is a specialization of the superty pe?In particular, how do we handle

- abstract types/classes?

- extensions of the state space?

The operational semantics provides a bad basis fordefining behavioral subtyping.

Problem:

Explanation: (Behavioral subtyping)

A subtype S is called a behavioral subtype of T iffS-objects behave according to the specification of T(auf Deutsch: S ist ein konformer Subtyp von T).

Page 46: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 175© A. Poetzsch-Heffter, TU Kaiserslautern

- Relation between Specifications & Implementations

- Pre- and postspecifications without abstract variables and without abstraction (concrete specs)

- Pre- and postspecifications with abstract variables and with abstraction (abstract specs)

- Treatment of invariants

- Treatment of frame properties

- Illustrating example

Overview:

• Behavioral subtyping depends on the specification.

• Main goal is to understand the relation betweensub- and supertypes.

• The described techniques should be applied to informal specifications/documentation as well.

Remark:

Kinds of Specialization:

- Refining implementation

- Refining nondeterminism

- Adding methods and extending state

Page 47: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 176© A. Poetzsch-Heffter, TU Kaiserslautern

Instead of relating an implementation of class D to the specifications of all its supertypes, we check that:

- the specifcation of D, spec(D), is a behavioral subtype of its direct supertype,

- the implementation of D, impl(D), satisfies spec(D ).

Relation between Specifications & Implementation

Illustration:

class C { pre PMC(this,p)post QMC(this,p,result)R m( T p ){ .../* impl(m,C) */ }

}

class D extends C { pre PMD(this,p)post QMD(this,p,result)R m( T p ){ .../* impl(m,D) */ }

}

Check:

a) { PMD(this,p) } impl(m,D) { QMD(this,p,resu lt) }

b) PMC(this,p) � PMD(this,p)

c) QMD(this,p,result) � QMC(this,p,result)

Page 48: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 177© A. Poetzsch-Heffter, TU Kaiserslautern

Specification languages usually support specificationinheritance in a form that establish (b) and (c) or refined versions of it.

Remark:

Example: (Spec. inheritance in JML)class C {

/*@ public normal_behavior@ requires PREMC@ ensures POSTMC ; @*/

R m( T p ){ ... }}

class D extends C { /*@ also

@ public normal_behavior@ requires PREMD@ ensures POSTMD ; @*/

R m( T p ){ ... }}

class D extends C { // not JML/*@ public normal_behavior

@ requires PREMC || PREMD@ ensures ( \old(PREMC) => POSTMC )@ && ( \old(PREMD) => POSTMD );@*/

R m( T p ){ ... }}

The specification of D is an abbreviation for:

Page 49: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 178© A. Poetzsch-Heffter, TU Kaiserslautern

Pre- and postconditions of methods in supertypesare valid pre-/postconditions for subtype methods:�

Inheritance of specification

Concrete Pre-Post-Specifications

Subtypes without Additional Attributes:

Inherited method:

- Specification is inherited without change.

Overriding method:

- Precondition inherited or new weaker precondition

- Postcondition inherited and possibly strengthenedby additional properties

Example:

class C { /*@ public normal_behavior

@ requires P@ ensures Q ;@*/

C m(){ ... }}

Page 50: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 179© A. Poetzsch-Heffter, TU Kaiserslautern

class D extends C { /*@ also

@ public normal_behavior@ requires P@ ensures \result instanceof D ;@*/

C m(){ ... }}

Remark:

Similar restrictions have to be applied to the specification of exceptional behavior.

Additional method:

- no constraints (but see about invariants).

Subtypes with Extended State:

If the state space is extended in the subtype,it can be necessary to strengthen the preconditionof overriding methods w.r.t. properties concerningthe additional attributes. However, this would viola te:

pre[Supertype] => pre[Subtype]

Page 51: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 180© A. Poetzsch-Heffter, TU Kaiserslautern

Solution for closed programs:

Include subtype properties in the specification of thesupertype and use the slightly weaker restrictions:

- pre[Supertype] && this instanceof Subtype => pre[Subtype]

- post[Subtype] && this instanceof Subtype => post[Supertype]

Remark:

• This technique can only be applied if supertypesknow their subtypes.

• A more practical and elegant solution for handlingextended state is to use abstraction.

Abstract Pre-Post-Specifications

The basic idea is to write specifications in terms of abstract states and to provide abstraction function s:

- from concrete objects to their abstract states

- from abstract states of subtype objects to abstrac tstates of supertype objects.

The abstraction functions in particular provide the flexiblity to handle extended state.

Here, we only consider an example:

Page 52: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 181© A. Poetzsch-Heffter, TU Kaiserslautern

Example:

class C { //@ public model boolean valid;//@ public model AS state;

/*@ public normal_behavior@ requires valid && r(state)@ ensures q(state) ;@*/

void m(){ ... }}

class D extends C { private BD d;

//@ private depends valid <- d;

//@ private represents valid <- CD.pd(d) ;

//@ private depends state <- d;

//@ private represents state <- CD.f(d) ; ...

}

class E extends C { private BE e;

//@ private depends valid <- e;

//@ private represents valid <- CE.pe(e) ;

//@ private depends state <- e;

//@ private represents state <- CE.g(e) ;

...

}

Page 53: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 182© A. Poetzsch-Heffter, TU Kaiserslautern

- pd is a predicate expressing when attribute dhas a valid state.

- f is an abstraction function mapping values of concrete type BD to the abstract type AS.

The definitions of pd and f can be tailored to theneeds of class D. The same holds for pe , g andclass E.

Remarks:

• Often one assumes an explicit abstractionfunction that maps values of subtype objects intothe state space of the supertype.

• Abstract/model variables enable two kinds of state extensions:

- overriding the representation function

- additional abstract variables

• The variations in the subtypes can be captured byrepresentation functions.

Page 54: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 183© A. Poetzsch-Heffter, TU Kaiserslautern

Treatment of Invariants

In principle, invariants can be expressed by pre- an dpostconditions. However, as a specification construct they allow to express restrictions on subtype behavior already in supertypes:

Invariants of supertypes have to be satisfied by additional subtype methods.

Example:

class C { public int a = 0;//@ public invariant a >= 0;...// no declaration of m

}

class D extends C { ...void m(){ a = -1; } // violates invariant...

}

Page 55: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 184© A. Poetzsch-Heffter, TU Kaiserslautern

Invariants of supertypes have to be satisfied by al lsubtype methods. This can be formulated as:

inv[Subtype] => inv[Supertype]

This can be achieved by invariant inheritance:�The subtype invariant is the conjunction of thesupertype invariant and additional invariant clauses specified in the subtype.

General Approach:

Problems:

- What is the precise meaning of an invariant?When should invariants hold?

- How is subtyping and dynamic binding handled for invariants?

There is no well-established answer to theseproblems. We discuss existing solutions.

Page 56: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 185© A. Poetzsch-Heffter, TU Kaiserslautern

Semantical variants:

1. Invariants have to hold in visible states:

JML: „Invariants have to hold in each state outsideof a public method‘s execution and at the beginningand end of such execution.“

2. Transformation into pre- and postconditions:

Invariants have to hold in poststates of constructo rs.If they hold in the prestate of a method, they have to hold in the poststate as well.

For verification, both variants are problematic:

Let S be a subtype of T, m be a method in T andx a variable of type T holding an S-object:

... x.m(...) ...

For the verification we need inv[S] as precondition.But: S may not be known at the invocation site.

Page 57: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 186© A. Poetzsch-Heffter, TU Kaiserslautern

Example:

class C { public int a = 0;//@ public invariant a >= 0;...void m(){ ... // maintains invariant}

}

class Foo {

void mfoo() {... x.m() ...

}}

class D extends C { public int b = 0;//@ public invariant a > 1;//@ public invariant b >= 0;...void m(){

b = 4 / a ;... // maintains both invariants}

}

Problem: What has to be shown for the prestate ofx.m()

Page 58: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 187© A. Poetzsch-Heffter, TU Kaiserslautern

Possible solution:

Consider as invariant of type T the followingformula INV[T]:

∀Type S: S ≤ T => ( type(this)=S => inv[S] )

where inv[S] is the invariant specified for the imp le-mentation of type S. Then we have for all subtypes Uof T:

typ(this) = U => ( inv[U] <=> INV[T] )

Treatment of Frame Properties

The specification of frame properties has to cope with two problems:

- Information hiding: not all assignable variablescan be named in the specification.

- Extended state: The supertype specificationcannot capture the state of additional attributes in subtypes.

Page 59: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 188© A. Poetzsch-Heffter, TU Kaiserslautern

Example:

class C { public int a = 0;private int b = 0;public static int c = 123;...

/*@ public normal_behavior@ assignable a;@*/

public void m(){ a++; b++ } }

class Foo {void mfoo() {

... x.m() ... }

}

class D extends C { public int d = 0;...public void m(){

super.m();d = 87;C.c = 4 ;

...}

}

Page 60: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 189© A. Poetzsch-Heffter, TU Kaiserslautern

�Use abstract attributes/variables,depends- and representation clauses.�Information Hiding: Abstract attributes can dependon non-accessible attributes.�Extended state: Depends relation can be extendedin subtypes.

Possible solution:

(Example is given in the following subsection)

Using the Techniques Together

Specification techniques for OO-programs have two goals:

- Specification of properties by annotating programs.

- Complete specification of types as basis for behavioral subtyping.

We illustrate this by a larger example.

Page 61: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 190© A. Poetzsch-Heffter, TU Kaiserslautern

Example:

The following example is a Java-version of the central example given in:

K. R. M. Leino, G. Nelson: Data abstraction and information hiding, Transactions on ProgrammingLanguages and Systems 24(5): 491-553 (2002).

Reader

BuffReader BlankReader

BlankReaderImpl

The example demonstrates:

- state extensions

- behavioral subtyping

Page 62: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 191© A. Poetzsch-Heffter, TU Kaiserslautern

public interface Reader {

//@ public model instance boolean valid;

//@ public model instance Object state;

/*@ public normal_behavior

@ requires valid;

@ assignable state;

@ ensures -1 <= \result

@ && \result < 65535 ;@*/

public int getChar();

/*@ public normal_behavior

@ requires valid;

@ assignable valid, state;@*/

public void close();

}

Page 63: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 192© A. Poetzsch-Heffter, TU Kaiserslautern

public abstract class BuffReader implements Reader {

protected /*@ spec_public @*/ int lo, cur, hi;protected /*@ spec_public @*/ char[] buff;

//@ public model boolean svalid;

/*@ public represents valid <-@ this != null &&@ 0 <= lo && lo <= cur && cur <= hi &&@ buff != null && hi-lo <= buff.length &&@ svalid ;@*/

public int getChar() {if( cur == hi ) refill();if( cur == hi ) return -1;cur++;return buff[cur-lo-1];

}

/*@ public normal_behavior@ requires valid;@ assignable state;@ ensures cur == \old(cur) ;@*/

public abstract void refill();

//@ depends valid <- lo,cur,hi, buff, svalid;//@ depends state <- lo,cur,hi, buff, buff[*];//@ depends svalid <-lo, hi, buff;

}

Page 64: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 193© A. Poetzsch-Heffter, TU Kaiserslautern

public interface BlankReader extends Reader {

/*@ public normal_behavior@ requires 0 <= n;@ assignable valid, state;@ ensures valid && \result == this ;@*/

public BlankReader init( int n );}

public class ReaderTest {

public static void main( String[] args ) {BlankReader br = new BlankReaderImpl();br.init(1000000);

int count = 0;int chr;do {

chr = br.getChar();count++;

} while( chr != -1 );br.close();System.out.println(count);

} }

A non-trivial application of BlankReader andBlankReaderImpl (s. next slide):

Page 65: 5. Subtyping and Inheritance - softech.cs.uni-kl.de · • Inheritance • Object-oriented type systems • Behavioral subtyping Remark: 5.1 Core Concepts Object-orientation has three

20.01.2006 194© A. Poetzsch-Heffter, TU Kaiserslautern

public class BlankReaderImplextends BuffReaderimplements BlankReader

{private int num;//@ private represents svalid <- hi <= num ;

public BlankReader init( int n ) {num = n;buff = new byte[ Math.min(n,8192) ];lo = 0;cur = 0;hi = buff.length;for( int i = 0; i < hi; i++ ) {

buff[i] = 32;}return this;

}

public void refill() {lo = cur;hi = Math.min( lo+buff.length, num );

}

public void close() {}

//@ private depends state <- num ;//@ private depends svalid <- num ;

// representation of state not// considered

}


Top Related