Download presentation
Presentation is loading. Please wait.
1
CPSC150 Interfaces Chapter 10.5-10.8
2
CPSC150 Inheritance Review No different than any other class. Has no access to or information about subclasses class SubClass1 extends SuperClass first line of constructor is super( ); can use methods from SubClass1 or SuperClass private in parent is not accessible to children; protected is Subclasses can have only one parent
3
CPSC150 Inheritance Review Two reasons for inheritance 1.To use the methods of the parent 2.To use polymorphism (e.g. add Item to a library, but each Item is a CD or Video)
4
CPSC150 Abstract Classes Review Abstract methods enable polymorphism, but have no body Classes with abstract methods must be abstract Abstract classes can not have objects created from them Abstract classes can have useful concrete methods (e.g., setComment) and fields (e.g., Xposition)
5
CPSC150 Abstract Class Review Two reasons for Abstract Classes 1.Enables polymorphism when methods are not appropriate for superclass (e.g., draw) 2.Enforces a specification (in order to be a Shape, you must have a draw method)
6
CPSC150 One more detail: Interfaces Allow multiple inheritance –Be an animal AND black (other things are animals and other things are black) Can specify exactly what is needed for a concrete class –actionPerformed
7
CPSC150 Interfaces To implement in interface (parent), put: –public interface MyInterface instead of public class MyInterface in class using interface (child), put: –public class SubClass1 extends SuperClass implements MyInterface
8
CPSC150 Two arrows
9
CPSC150 Interfaces concept Just like a class, –but no variables (can have static final public fields) –no bodies for ANY method Like abstract class on speed Purpose? –polymorphism –specification
10
CPSC150 Interface Examples Comparator ActionListener
11
CPSC150 Abstract Classes vs Interfaces Use interfaces when possible because there can lots of classes following "implements" but only one "extends" Use interfaces if you do not want any fields or methods in your parent class Use abstract classes if you want subclasses to use common defined methods or fields
12
CPSC150 Problem 10.54 Look at the code below. You have five types (classes or interfaces) U, G, B, Z, and X, and a variable of each of these types. What can you say about the relationships of the types? U u; G g; B b; Z z; X x; The following assignments are all legal: u = z; x = b; g = u; x = u; The following assignments are all illegal (they cause compiler errors): u = b; x = g; b = u; z = u; g = x;
13
CPSC150 Wrapper Classes, 8.9.3 Many times an object is wanted instead of a primitive. Use a wrapper class: wraps the primitive around a java.lang wrapper class int i = 20; Integer iwrap = new Integer(i); myCollection.add(iwrap); // added as an Integer int iwrapvalue = iwrap.intValue( 37);
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.