tut04 - CS1020 Data Structures and Algorithms I Tutorial 4 Abstract Data Types(For week 6 starting 17 February 2014 1[Abstract classes vs Interfaces An

tut04 - CS1020 Data Structures and Algorithms I Tutorial 4...

This preview shows page 1 - 3 out of 8 pages.

CS1020: Data Structures and Algorithms I 1 Tutorial 4 – Abstract Data Types (For week 6, starting 17 February 2014) 1. [Abstract classes vs. Interfaces] An abstract class is one that contains some abstract methods (abstract methods are methods without implementation). Below is an example of an abstract class, AbstractComplex , which you can extend as the ComplexCart and ComplexPolar classes. Contrast this with the interface Complex found in your lecture notes. public abstract class AbstractComplex { public abstract double realpart(); // returns real public abstract double imagpart(); // returns imag public abstract double angle(); // returns angle public abstract double mag(); // returns mag public abstract void add(AbstractComplex c); // this=this+c public abstract void minus(AbstractComplex c); // this=this-c public abstract void times(AbstractComplex c); // this=this*c /* Since toString is same for both Cartesian and Polar forms, we can implement it here to avoid implementing it twice in the Cartesian and Polar subclasses. */ @Override public String toString() { return stringForm(); } /* We can even make private methods! */ private String stringForm() { if (imagpart() == 0) return (realpart() + "" ); else if (imagpart() < 0) return (realpart() + "" + imagpart() + "i" ); else return (realpart() + "+" + imagpart() + "i" ); } } a. What are the differences between abstract classes and interfaces? (You can compare the abstract class AbstractComplex above with the interface Complex in your lecture notes, but there are more differences than what we have shown.) b. When should we use an interface instead of an abstract class, and vice versa? c. The Java library has specified a few interfaces that it uses to perform commonly used tasks. Find out what the following interfaces are used for, and give an example of when they are used: i. Comparable ii. Iterable
Image of page 1