Lec 25 - Subtyping and Dynamic Dispatch

Calling super workspace stack super thisy inity heap

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: c void incBy(int d) { this.x = this.x + d; }! public int get() { return this.x; }! }! public class Decr extends Counter {! private int y;! public Decr (int initY) { super(); this.y = initY; }! public void dec() { this.incBy(-this.y); }! }! // … somewhere in main:! Decr d = new Decr(2);! d.dec();! int x = d.get();! Construccng an Object Workspace Decr d = new Decr(2);! d.dec();! int x = d.get();! Stack Heap Class Table Object! String toString(){… ! boolean equals…! …! Counter! extends ! Counter() { x = 0; }! void incBy(int d){…}! int get() {return x;}! Decr! extends ! Decr(int initY) { … }! void dec(){incBy(-y);}! Allocacng Space on the Heap! Workspace Stack Heap super();! this.y = initY;! Decr d = _;! d.dec();! int x = d.get();! Class Table Decr! Object! x! initY! Invoking a constructor: •  allocates space for a new object in the heap •  includes slots for all fields of all ancestors in the class tree (here: x and y) •  creates a pointer to the class – this is the object’s dynamic type •  runs the constructor body aier pushing parameters and this onto the stack String toString(){… ! y! this! 0! 0! boolean equals…! 2! …! Counter! extends Object ! Counter() { x = 0; }! void incBy(int d){…}! int get() {return x;}! Note: fields start with a “sensible” default - 0 for numeric values - null for references Decr! extends Counter ! Decr(int initY) { … }! void dec(){incBy(-y);}! Calling super! Workspace Stack super();! this.y = initY;! Heap Decr d = _;! d.dec();! int x = d.get();! Class Table Decr! Object! x! initY! 2! String toString(){… ! y! this! 0! 0! boolean equals…! …! Counter! extends Object ! Call to super: •  The constructor (implicitly) calls the super construct...
View Full Document

This note was uploaded on 10/23/2012 for the course CIS 121 taught by Professor Tannen during the Spring '09 term at UPenn.

Ask a homework question - tutors are online