Lec 25 - Subtyping and Dynamic Dispatch

It takes a few steps body of incby reads thisx

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: dispatch – which code is run depends on the dynamic type of the object. (In this case, Decr.) void incBy(int d){…}! int get() {return x;}! Search through the methods of the Decr, class trying to find one called dec. Decr! extends Counter ! Decr(int initY) { … }! void dec(){incBy(-y);}! Dynamic Dispatch: Finding the Code Workspace this.incBy(-this.y);! Stack d! Heap Class Table Decr! Object! x! 0! String toString(){… ! y! _;! int x = d.get();! 2! boolean equals…! this! …! Counter! extends Object ! Call the method, remembering the current workspace and pushing the this pointer and any arguments (none in this case). Counter() { x = 0; }! void incBy(int d){…}! int get() {return x;}! Decr! extends Counter ! Decr(int initY) { … }! void dec(){incBy(-y);}! Reading A Field’s Contents Workspace this.incBy(- .y);! Stack d! Heap Class Table Decr! Object! x! 0! String toString(){… ! y! _;! int x = d.get();! 2! boolean equals…! this! …! Counter! extends Object ! Read from the y slot of the object. Counter() { x = 0; }! void incBy(int d){…}! int get() {return x;}! Decr! extends Counter ! Decr(int initY) { … }! void dec(){incBy(-y);}! Dynamic Dispatch, Again Workspace .incBy(-2);! Stack d! Heap Class Table Decr! Object! x! 0! String toString(){… ! y! _;! int x = d.get();! 2! boolean equals…! this! …! Invoke the incBy method on the object via dynamic dispatch. Counter! In this case, the incBy met...
View Full Document

Ask a homework question - tutors are online