Lec 25 - Subtyping and Dynamic Dispatch

Public void copyfc other thisf otherf an

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:   When a program starts, the JVM inicalizes the class table Each class has a pointer to its (unique) parent in the class tree A class stores the constructor and method code for its instances The class also stores sta6c members •  Constructors: –  Allocate space in the heap –  (Implicitly) invoke the super class constructor, then run the constructor body •  Objects and their methods: –  Each object in the heap has a pointer to the class table of its dynamic (the one it was created with via new). –  A method invocacon “o.m(…)” uses o’s class table to “dispatch” to the appropriate method code (might involve searching up the class hierarchy). –  Methods and constructors take an implicit “this” parameter, which is a pointer to the object whose method was invoked. Fields& methods are accessed with this. The ‘this’ Reference •  Inside a non- stacc method, the variable this is a reference to the object itself. •  References to local fields and methods have an implicit “this.” in front of them. class C {! !private int f;! !public void copyF(C other) {! ! !this.f = other.f;! !}! }! An Example public class Counter {! private int x;! public Counter () { x = 0; }! public void incBy(int d) { x = x + d; }! public int get() { return x; }! }! public class Decr extends Counter {! private int y;! public Decr (int initY) { y = initY; }! public void dec() { incBy(-y); }! }! // … somewhere in main:! Decr d = new Decr(2);! d.dec();! int x = d.get();! Example with Explicit this and super! public class Counter extends Object {! private int x;! public Counter () { super(); this.x = 0; }! publi...
View Full Document

Ask a homework question - tutors are online