390 likes | 610 Views
Chapter 14. Abstract Classes and Interfaces. Abstract Classes. An abstract class extracts common features and functionality of a family of objects An abstract class provides a uniform interface for dealing with a family of objects Abstract classes are defined with the abstract keyword.
E N D
Chapter 14 Abstract Classes and Interfaces
Abstract Classes • An abstract class extracts common features and functionality of a family of objects • An abstract class provides a uniform interface for dealing with a family of objects • Abstract classes are defined with the abstract keyword
Using abstract classes • Concrete instances of abstract classes cannot be instantiated with the new operator • However, variables of abstract class types can be declared and used to hold objects that extend (inherit from) the abstract class • Abstract classes can have constructors that are called by subtypes using the super keyword (even though they cannot be created)
Abstract Methods • Methods can be defined using the abstract keyword • If a class contains abstract methods, the class must be declared abstract as well • Abstract methods do not have a body • Abstract methods are implemented by subclasses • If a subclass does not implement all abstract methods in the superclass, it must be declared abstract
What is the purpose? • Abstract methods define a common interface that all subclasses will implement • The methods can be called on a supertype variable using polymorphism without regard to what actual subtype is stored in the variable. • Allows generic treatment of a family of subtypes
Other points of interest • An abstract class does not have to define any abstract methods • A subclass can be defined abstract even if the superclass is concrete (e.g. java.lang.Object) • A subclass can override a superclass method and define it to be abstract
Interfaces • Interfaces are like abstract classes—but • Interfaces are declared with the interface keyword • Interfaces can only define abstract methods • Interfaces can only declare constants • Interfaces are compiled into separate byte-code files just like classes
How to use interfaces • A class can extend only one class by inheritance (using the extends keyword) • A class can implement an unlimited number of interfaces (using the implements keyword) • An interface is “contract” of functionality • Classes can be designed to use and provide specific functionality via an defined interface (the Application Programming Interface)
Java and Multiple Inheritance • Java does not support inheriting from multiple classes (linear inheritance model) • This avoids many problems encountered in C++ • Java can simulate multiple inheritance by having a class implement multiple interfaces that provide the functionality of multiple “class abstractions”
The Comparable interface • public interface Comparable { public intcompareTo(Object o); } • Classes implementing this interface can be compared to each other to obtain an ordering relationship • public class MyClass extends Object implements Comparable { public intcompareTo(Object o) { // code to compare objects } }
A Caveat • compareTo() returns zero if two objects have the same ordering relationship • Generally, this would imply that the overriden equals() method inherited from java.lang.Object would also return true for the two objects • Often the implementations will be congruent, but not always
ActionListener • ActionListener is an interface for handling GUI events such as button clicks • A class that implements ActionListeneroverrides the actionPerformed() method to provide custom processing to respond to GUI events • A GUI element “adds” an object implementing ActionListener and then sends events (e.g. button clicks) to the object for processing through the actionPerformed() method
How does ActionListener work? • Explain how ActionListener works under the covers if students do not appear too restless or bored • Is event handling in Java kind of like a “come from” statement (opposite of goto)? • ActionListeners are often implemented as anonymous inner classes--but that is a topic for next semester!
The Cloneable Interface • Cloneable is an empty interface (no methods or constants defined) • Empty interfaces are called marker interfaces and signal that an object implements certain characteristics • In this case, Cloneable indicates that the class overrides the clone() method defined for java.lang.Object
clone() • The definition of clone() is: protected native Object clone() throws CloneNotSupportedException; • Cloning relies on the underlying system to create a copy of an object—native code • clone() is a protected method, but it can be made public when overriden • clone() can throw an exception that you should handle
Shallow Copy • The overriden method clone() can be implemented by calling super.clone() • Implementing it this way does a shallow copy • A shallow copy will copy the contents of each field of the object to the new object • The value of primitive types are copied • The references to objects are copied • References will be equal even though the cloned objects are not equal
Deep Copy • A deep copy creates duplicates of the objects referenced by fields rather than simply copying the references • Deep copy is implemented by first calling super.clone() and then adding code to duplicate objects • Deep copy is important if the two objects modify internal objects and should not be using the same objects
Multithreading • Multithreading means running two different paths of execution simultaneously • Java has two ways to do multithreading: the good way and the other way • The good way is to implement the Runnable interface • The other way is to extend the Thread class (if you need to override its methods)
Runnable • The Runnable interface has just one method: void run(); // no parameters • The run() method is where thread execution starts, which is effectively the main method for the thread • A class that implements Runnable can create a Thread with itself as the parameter and run itself in a thread
Interface vs. Abstract Class Interface Abstract Class No restrictions on variables Constructors are allowed and can be invoked by subclasses No restrictions on methods • All variables must be public static final • Constructors are not allowed • All methods must be public abstract
When to use • An abstract class represents common functionality extracted from a family of related objects • An interface represents common functionality that can be implemented by unrelated objects • What are some examples typifying this division of usage?
Primitive Data Types as Objects • All primitive data types can be represented as objects • Doing this would make the language perfectly uniform • It would also make the language very slow • Wrapper Classes are the objects that “wrap” primitive data types • Wrapper classes allow generic programming
Wrapper Classes • Boolean • Character • Byte • Short • Integer • Long • Float • Double
Number • The numeric wrapper classes extend the abstract Number class • Number has methods to convert a value to various primitive types • Each wrapper class overrides the toString(), equals() and compareTo() methods • Each wrapper class knows the MAX_VALUE and MIN_VALUE for the types it wraps
Conversion methods • shortValue() • intValue() • longValue() • floatValue() • doubleValue() • valueOf(String strValue) // returns an object initialized with the value specified in strValue
Parsing methods • public static xyz parseXyz(String s) • public static xyz parseXyz(String s, int radix) • Static methods called on wrapper class Integer.parseInt(“536”, 16); • Returns the primitive type (xyz) represented by the string • Can choose a radix value of 2, 8, 10, or 16 (the default is 10)*
BigInteger and BigDecimal • Java provides two classes for handling very large or very precise numbers • BigInteger and BigDecimal can represent numbers of any size or precision* • Both classes implement add(), subtract(), multiply(), divide(), and remainder() • Both implement compareTo() • Be careful with BigDecimal.divide()*
CS4a Lab 1 reduxCalculating Pi using BigDecimal • The irrational number pi can be calculated by the following formula: • Pi = ) • Calculate and store this value in a BigDecimalvariable • Expand the formula to 20 digits of precision • Display the results either on the console or in a dialog box
Problems to consider • Will this require doing arithmetic with more digits of precision that just 20? • What kinds of cumulative errors have we discussed in class that need to be avoided? • How many digits of calculation precision will be required to accurately define 20 digits of pi? • How many terms need to be expanded?
Details • Remember to have a cover sheet and include appropriate comments and printouts of the results. • Assignment due: 4:30 p.m. November 1, 2012