

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


[http://6170.lcs.mit.edu/www-archive/Old-Fall03/lectures/handout/lec03_subclassing.pdf] [http://www.cs.sunysb.edu/~cse219/lectures/5 ]
Note that given an Account and AccountPlus class that extends Account, we can create an array of Account objects, where at run time it is determined whether each one is an Account or an AccountPlus instance public static void main(String[] args) { Account [ ] accounts = new Account[3]; accounts[0] = new Account("checking"); accounts[1] = new AccountPlus("checkguard", 200); accounts[2] = new Account("savings"); // charge the monthly fee for each account for (int i = 0; i < accounts.length; i++) { Trans fee = new Trans(-1, new Date()); if (accounts[i].checkTrans(fee)) accounts[i].post(fee); }// end for }
In the example above, each of the three accounts instances have an apparent type of Account , however accounts[1] has an actual type of AccountPlus. Only the apparent type’s methods are available. Remember that Java guarantees the apparent type of any object is a supertype of its actual type Examples: what are the apparent type and actual type of each of the following? Vector v = new Vector(); // what are v’s apparent & actual types? Object o1 = v; // what are o1’s apparent & actual types? int[] a = {1, 2}; Object o2 = a; // what are o2’s apparent & actual types?
Dispatching Dispatching in Functional Languages (e.g. C) At compile time, the destination method is known. At compile time, a method call is translated into a jump/branch command to a pre-calculated address. We can't do that in Java, since the type of the calling object may not be know until run-time. Dispatching in Java