48
Chapter 14 Abstract Classes and Interfaces 1

Chapter 14 Abstract Classes and Interfaces

Embed Size (px)

DESCRIPTION

Chapter 14 Abstract Classes and Interfaces. 1. Objectives. To design and use abstract classes (§14.2). To process a calendar using the Calendar and GregorianCalendar classes (§14.3). To specify common behavior for objects using interfaces (§14.4). - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 14 Abstract Classes and Interfaces

Chapter 14 Abstract Classes and Interfaces

1

Page 2: Chapter 14 Abstract Classes and Interfaces

Objectives To design and use abstract classes (§14.2).

To process a calendar using the Calendar and GregorianCalendar classes (§14.3).

To specify common behavior for objects using interfaces (§14.4).

To define interfaces and define classes that implement interfaces (§14.4).

To explore the similarities and differences between an abstract class and an interface (§14.8).

To create objects for primitive values using the wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, and Boolean) (§14.9).

To simplify programming using automatic conversion between primitive types and wrapper class types (§14.11).

2

Page 3: Chapter 14 Abstract Classes and Interfaces

3

Abstract Classes Now suppose we want to create a super class wherein it has certain methods that contains some implementation, and some methods wherein we just want to be overridden by its subclasses.

For example, we want to create a super class named Living Thing. This class has certain methods like breath, eat, sleep and walk. However, there are some methods in this super class wherein we cannot generalize the behavior. Take for example, the walk method. Not all living things walk the same way. Take the humans for instance, we humans walk on two legs, while other living things like dogs walk on four legs. However, there are many characteristics that living things have in common, that is why we want to create a general super class for this.

Page 4: Chapter 14 Abstract Classes and Interfaces

4

In order to do this, we can create a super class that has some methods with implementations and others which do not. This kind of class is called an abstract class.

An abstract class is a class that cannot be instantiated. It often appears at the top of an object-oriented programming class hierarchy, defining the broad types of actions possible with objects of all subclasses of the class.

Figure 1: Abstract class

Page 5: Chapter 14 Abstract Classes and Interfaces

5

Abstract Classes and Abstract Methods GeometricObject

-color: String

-filled: boolean

-dateCreated: java.util.Date

#GeometricObject()

#GeometricObject(color: string, filled: boolean)

+getColor(): String

+setColor(color: String): void

+isFilled(): boolean

+setFilled(filled: boolean): void

+getDateCreated(): java.util.Date

+toString(): String

+getArea(): double

+getPerimeter(): double

Circle

-radius: double

+Circle()

+Circle(radius: double)

+Circle(radius: double, color: string, filled: boolean)

+getRadius(): double

+setRadius(radius: double): void

+getDiameter(): double

Rectangle -width: double

-height: double

+Rectangle()

+Rectangle(width: double, height: double)

+Rectangle(width: double, height: double, color: string, filled: boolean)

+getWidth(): double

+setWidth(width: double): void

+getHeight(): double

+setHeight(height: double): void

The # sign indicates protected modifier

Abstract class

Abstract methods are italicized

Methods getArea and getPerimeter are overridden in Circle and Rectangle. Superclass methods are generally omitted in the UML diagram for subclasses.

Page 6: Chapter 14 Abstract Classes and Interfaces

6

/** Return filled. Since filled is boolean, * the get method is named isFilled */ public boolean isFilled() { return filled; } /** Set a new filled */ public void setFilled(boolean filled) { this.filled = filled; } /** Get dateCreated */ public java.util.Date getDateCreated() { return dateCreated; }/** Return a string representation of this object */ public String toString() { return "created on " + dateCreated + "\ncolor: " + color + " and filled: " + filled; } // Abstract method getArea (No implementation) public abstract double getArea();

//Abstract method getPerimeter public abstract double getPerimeter();}

public abstract class GeometricObject { private String color = "white"; private boolean filled; private java.util.Date dateCreated; /** Construct a default geometric object */ protected GeometricObject() { dateCreated = new java.util.Date(); } /** Construct a geometric object with color and filled value */ protected GeometricObject(String color, boolean filled) { dateCreated = new java.util.Date(); this.color = color; this.filled = filled; } /** Return color */ public String getColor() { return color; }/** Set a new color */ public void setColor(String color) { this.color = color; }

Page 7: Chapter 14 Abstract Classes and Interfaces

7

public class Circle extends GeometricObject { private double radius;

public Circle() { }

public Circle(double radius) { this.radius = radius; }

/** Return radius */ public double getRadius() { return radius; }

/** Set a new radius */ public void setRadius(double radius) { this.radius = radius; }

/** Return area */ public double getArea() { return radius * radius * Math.PI; }

/** Return diameter */ public double getDiameter() { return 2 * radius; }

/** Return perimeter */ public double getPerimeter() { return 2 * radius * Math.PI; }

/* Print the circle info */ public void printCircle() { System.out.println("The circle is created " + getDateCreated() + " and the radius is " + radius); }}

Page 8: Chapter 14 Abstract Classes and Interfaces

8

public class Rectangle extends GeometricObject { private double width; private double height;

public Rectangle() { }

public Rectangle(double width, double height) { this.width = width; this.height = height; }

/** Return width */ public double getWidth() { return width; }

/** Set a new width */ public void setWidth(double width) { this.width = width; }

/** Return height */ public double getHeight() { return height; }

/** Set a new height */ public void setHeight(double height) { this.height = height; }

/** Return area */ public double getArea() { return width * height; }

/** Return perimeter */ public double getPerimeter() { return 2 * (width + height); }}

Page 9: Chapter 14 Abstract Classes and Interfaces

Why Abstract methods?Q: what advantage is gained by defining the

methods getArea and getPerimeter as abstract in the GeometricObject class instead of defining them only in each subclass?

9

Page 10: Chapter 14 Abstract Classes and Interfaces

10

public class TestGeometricObject { /** Main method */ public static void main(String[] args) { // Declare and initialize two geometric objects GeometricObject geoObject1 = new Circle(5); GeometricObject geoObject2 = new Rectangle(5, 3); System.out.println("The two objects have the same area? " + equalArea(geoObject1, geoObject2)); // Display circle displayGeometricObject(geoObject1); // Display rectangle displayGeometricObject(geoObject2); } /** A method for comparing the areas of two geometric objects */ public static boolean equalArea(GeometricObject object1, GeometricObject object2) { return object1.getArea() == object2.getArea(); } /** A method for displaying a geometric object */ public static void displayGeometricObject(GeometricObject object) { System.out.println(); System.out.println("The area is " + object.getArea()); System.out.println("The perimeter is " + object.getPerimeter()); }}

Page 11: Chapter 14 Abstract Classes and Interfaces

So, the advantage is … ?You could not define the equalArea method

for comparing whether two geometric objects have the same area if the getArea method were not defined in GeometricObject.

11

Page 12: Chapter 14 Abstract Classes and Interfaces

12

Abstract classes & methods• An abstract method cannot be contained in a non-abstract class. If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be defined abstract.

• In other words, in a non-abstract subclass extended from an abstract class, all the abstract methods must be implemented, even if they are not used in the subclass.

• Bottom line is: A class that contains abstract methods must be defined abstract, and ALL abstract methods must be implemented in the subclass.

Page 13: Chapter 14 Abstract Classes and Interfaces

13

Object cannot be created from an abstract class • An abstract class cannot be instantiated using the new operator, but you can still define its constructors, which are invoked in the constructors of its subclasses.

• For example, the constructors of GeometricObject are invoked in the Circle class and the Rectangle class.

Page 14: Chapter 14 Abstract Classes and Interfaces

14

Abstract class without abstract method

• A class that contains abstract methods must be abstract.

• However, it is possible to define an abstract class that contains no abstract methods.

• In this case, you cannot create instances of the class using the new operator. This class is used as a base class for defining a new subclass.

Page 15: Chapter 14 Abstract Classes and Interfaces

15

Superclass of abstract class may be concrete • A subclass can be abstract even if its superclass is concrete.

• For example, the Object class is concrete, but its subclasses, such as GeometricObject, may be abstract.

Page 16: Chapter 14 Abstract Classes and Interfaces

16

Concrete method overridden to be abstract • A subclass can override a method from its superclass to define it abstract.

• This is very rare, but useful when the implementation of the method in the superclass becomes invalid in the subclass.

• In this case, the subclass must be defined abstract.

Page 17: Chapter 14 Abstract Classes and Interfaces

17

Abstract class as Data Type • You cannot create an instance from an abstract class using the new operator, but an abstract class can be used as a data type.

• Therefore, the following statement, which creates an array whose elements are of GeometricObject type, is correct.

GeometricObject[] geo = new GeometricObject[10];

• You can then create an instance of GeometricObject and assign its reference to the array like this:

objects[0] = new Circle();

Page 18: Chapter 14 Abstract Classes and Interfaces

18

The Abstract Calendar Class and Its GregorianCalendar subclass

java.util.GregorianCalendar

+GregorianCalendar()

+GregorianCalendar(year: int, month: int, dayOfMonth: int)

+GregorianCalendar(year: int, month: int, dayOfMonth: int, hour:int, minute: int, second: int)

Constructs a GregorianCalendar for the current time.

Constructs a GregorianCalendar for the specified year, month, and day of month.

Constructs a GregorianCalendar for the specified year, month, day of month, hour, minute, and second. The month parameter is 0-based, that is, 0 is for January.

java.util.Calendar

#Calendar()

+get(field: int): int

+set(field: int, value: int): void

+set(year: int, month: int, dayOfMonth: int): void

+getActualMaximum(field: int): int

+add(field: int, amount: int): void

+getTime(): java.util.Date

+setTime(date: java.util.Date): void

Constructs a default calendar.

Returns the value of the given calendar field.

Sets the given calendar to the specified value.

Sets the calendar with the specified year, month, and date. The month parameter is 0-based, that is, 0 is for January.

Returns the maximum value that the specified calendar field could have.

Adds or subtracts the specified amount of time to the given calendar field.

Returns a Date object representing this calendar’s time value (million second offset from the Unix epoch).

Sets this calendar’s time with the given Date object.

Page 19: Chapter 14 Abstract Classes and Interfaces

19

The Abstract Calendar Class and its GregorianCalendar subclass

An instance of java.util.Date represents a specific instant in time with millisecond precision (the milliseconds since January 1, 1970, 00:00:00 GMT). Most of the methods in Date are deprecated (for lack of internationalization support). Date class is sufficient if you just need a simple timestamp. java.util.Calendar is an abstract base class for extracting detailed information such as year, month, date, hour, minute and second. Subclasses of Calendar can implement specific calendar systems such as Gregorian calendar, Lunar Calendar and Jewish calendar. Currently, java.util.GregorianCalendar for the Gregorian calendar is supported in the Java API.

Page 20: Chapter 14 Abstract Classes and Interfaces

20

The GregorianCalendar ClassYou can use new GregorianCalendar() to construct a default GregorianCalendar with the current time and use new GregorianCalendar(year, month, date) to construct a GregorianCalendar with the specified year, month, and date. The month parameter is 0-based, i.e., 0 is for January.

Page 21: Chapter 14 Abstract Classes and Interfaces

21

The get Method in Calendar ClassThe get(int field) method defined in the Calendar class is useful to extract the date and time information from a Calendar object. The fields are defined as constants, as shown in the following.

Constant Description

The year of the calendar.

The month of the calendar with 0 for January.

The day of the calendar.

The hour of the calendar (12-hour notation).

The hour of the calendar (24-hour notation).

The minute of the calendar.

The second of the calendar.

The day number within the week with 1 for Sunday.

Same as DATE.

The day number in the year with 1 for the first day of the year.

The week number within the month.

The week number within the year.

Indicator for AM or PM (0 for AM and 1 for PM).

YEAR

MONTH

DATE

HOUR

HOUR_OF_DAY

MINUTE

SECOND

DAY_OF_WEEK

DAY_OF_MONTH

DAY_OF_YEAR

WEEK_OF_MONTH

WEEK_OF_YEAR

AM_PM

Page 22: Chapter 14 Abstract Classes and Interfaces

ExampleCalendar calendar = new GregorianCalendar();

System.out.println("YEAR:\t" + calendar.get(Calendar.YEAR)); System.out.println("MONTH:\t" + calendar.get(Calendar.MONTH));System.out.println("DATE:\t" + calendar.get(Calendar.DATE));System.out.println("HOUR:\t" + calendar.get(Calendar.HOUR));

// Construct a calendar for April 15, 2012Calendar calendar1 = new GregorianCalendar(2012, 15, 3);

22

Page 23: Chapter 14 Abstract Classes and Interfaces

InterfacesWhat is an interface?Why is an interface useful?How do you define an interface?How do you use an interface?

23

Page 24: Chapter 14 Abstract Classes and Interfaces

24

What is an interface? Why is an interface useful?

An interface is a class like construct that contains only constants and abstract methods. In many ways, an interface is similar to an abstract class, but the intent of an interface is to specify behavior for objects (share common behavior). For example, you can specify that the objects are comparable, edible, cloneable using appropriate interfaces. Edible means fit to be eaten, especially by humans.

Page 25: Chapter 14 Abstract Classes and Interfaces

25

Define an InterfaceTo distinguish an interface from a class, Java uses the following syntax to define an interface:

public interface InterfaceName { constant declarations; method signatures;}

Example:

public interface Edible {

/** Describe how to eat */

public abstract String howToEat();

}

Page 26: Chapter 14 Abstract Classes and Interfaces

26

Interface is a Special Class An interface is treated like a special class in Java.

Each interface is compiled into a separate bytecode file, just like a regular class.

Like an abstract class, you cannot create an instance from an interface using the new operator, but in most cases you can use an interface more or less the same way you use an abstract class.

For example, you can use an interface as a data type for a variable, as the result of casting, and so on.

Page 27: Chapter 14 Abstract Classes and Interfaces

27

ExampleYou can now use the Edible interface to specify whether an object is edible. This is accomplished by letting the class for the object implement this interface using the implements keyword.

For example, the classes Chicken and Fruit implement the Edible interface (See TestEdible).

Page 28: Chapter 14 Abstract Classes and Interfaces

28

public interface Edible { /** Describe how to eat */ public abstract String howToEat(); }

• Note: When a class implements an interface, it implements all the methods defined in the interface with the exact signature and return type.

Page 29: Chapter 14 Abstract Classes and Interfaces

29

public class TestEdible { public static void main(String[] args) { Object[] objects = {new Tiger(), new Chicken(), new Apple()}; for (int i = 0; i < objects.length; i++) if (objects[i] instanceof Edible) System.out.println(((Edible)objects[i]).howToEat()); }}

class Animal { // Data fields, constructors, and methods omitted }class Chicken extends Animal implements Edible { public String howToEat() { return "Chicken: Fry it"; }}class Tiger extends Animal { …. }

abstract class Fruit implements Edible { // Data fields, constructors, and methods omitted here}

class Apple extends Fruit { public String howToEat() { return "Apple: Make apple cider"; }}

class Orange extends Fruit { public String howToEat() { return "Orange: Make orange juice"; }}

Page 30: Chapter 14 Abstract Classes and Interfaces

30

Omitting Modifiers in InterfacesAll data fields are public final static and all methods are public abstract in an interface. For this reason, these modifiers can be omitted, as shown below:

public interface T1 { public static final int K = 1; public abstract void p(); }

Equivalent public interface T1 { int K = 1; void p(); }

A constant defined in an interface can be accessed using syntax InterfaceName.CONSTANT_NAME (e.g., T1.K).

Page 31: Chapter 14 Abstract Classes and Interfaces

31

Interfaces vs. Abstract ClassesIn an interface, the data must be constants; an abstract class can have all types of data.

Each method in an interface has only a signature without implementation; an abstract class can have concrete methods.

Variables Constructors Methods

Abstract class

No restrictions Constructors are invoked by subclasses through constructor chaining. An abstract class cannot be instantiated using the new operator.

No restrictions.

Interface All variables must be public static final

No constructors. An interface cannot be instantiated using the new operator.

All methods must be public abstract instance methods

Page 32: Chapter 14 Abstract Classes and Interfaces

32

Interfaces vs. Abstract Classes, cont.• All classes share a single root, the Object class, but there is no single root for interfaces.

• Like a class, an interface also defines a type. A variable of an interface type can reference any instance of the class that implements the interface.

• If a class implements an interface, this interface is like a superclass for the class.

• You can use an interface as a data type and cast a variable of an interface type to its subclass, and vice versa.

Page 33: Chapter 14 Abstract Classes and Interfaces

Example:Suppose that c is an instance of Class2. c is also an

instance of Object, Class1, Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2.

33

Object Class1

Interface1 Interface1_1

Interface1_2

Class2

Interface2_1

Interface2_2

Page 34: Chapter 14 Abstract Classes and Interfaces

34

Caution: Conflict Interfaces

In rare occasions, a class may implement two interfaces with conflict information (e.g., two same constants with different values or two methods with same signature but different return type). This type of errors will be detected by the compiler.

Page 35: Chapter 14 Abstract Classes and Interfaces

35

Whether to use an interface or a class? Abstract classes and interfaces can both be used to model common features.

In general, a strong is-a relationship that clearly describes a parent-child relationship should be modeled using classes.

For example, a staff member is a person. So their relationship should be modeled using class inheritance.

A weak is-a relationship, also known as an is-kind-of relationship, indicates that an object possesses a certain property. A weak is-a relationship can be modeled using interfaces.

For example, all fruits are edible, so the Fruit class implements the Edible interface.

You can also use interfaces to circumvent single inheritance restriction if multiple inheritance is desired. In the case of multiple inheritance, you have to design one as a superclass, and others as interface.

Page 36: Chapter 14 Abstract Classes and Interfaces

Interface vs. InheritanceThe Java interface is used to share common behavior

(only method headers) among the instances of different classes.

Inheritance is used to share common code (including both data members and methods) among the instances of related classes.

In your program designs, remember to use the Java interface to share common behavior. Use inheritance to share common code.

36

Page 37: Chapter 14 Abstract Classes and Interfaces

Processing Primitive Data Type values as Objects many Java methods require the use of

objects as arguments. For example, the add(object) method in the

ArrayList class adds an object to an ArrayList.Java offers a convenient way to incorporate,

or wrap, a primitive data type into an object. Ex: wrapping int into the Integer class. By using a wrapper object instead of a

primitive data type variable, you can take advantage of generic programming.

37

Page 38: Chapter 14 Abstract Classes and Interfaces

38

Wrapper Classes• Boolean

• Character

• Short

• Byte

• Integer• Long

• Float

• Double

java.lang.Object

-

Double -

Float -

Long -

Integer -

Short -

Byte -

Character -

Boolean -

Number -

java.lang.Comparable -

NOTE: (1) The wrapper classes do not have no-arg constructors. (2) The instances of all wrapper classes are immutable, i.e., their internal values cannot be changed once the objects are created.

Page 39: Chapter 14 Abstract Classes and Interfaces

39

The toString, equals Methods

Each wrapper class overrides the toString, equals, methods defined in the Object class. Since all the numeric wrapper classes and the Character class implement the Comparable interface, the compareTo method is implemented in these classes.

Page 40: Chapter 14 Abstract Classes and Interfaces

40

The Number Class Each numeric wrapper class extends the abstract Number class, which contains the methods doubleValue, floatValue, intValue, longValue, shortValue, and byteValue.

These methods “convert” objects into primitive type values.

The methods doubleValue, floatValue, intValue, longValue are abstract.

The methods byteValue and shortValue are not abstract, which simply return (byte)intValue() and (short)intValue(), respectively.

Page 41: Chapter 14 Abstract Classes and Interfaces

41

The Integer and Double Classes

java.lang.Integer

-value: int +MAX_VALUE: int +MIN_VALUE: int +Integer(value: int) +Integer(s: String) +valueOf(s: String): Integer +valueOf(s: String, radix: int): Integer +parseInt(s: String): int +parseInt(s: String, radix: int): int

java.lang.Number +byteValue(): byte +shortValue(): short +intValue(): int +longVlaue(): long +floatValue(): float +doubleValue():double

java.lang.Double

-value: double +MAX_VALUE: double +MIN_VALUE: double +Double(value: double) +Double(s: String) +valueOf(s: String): Double +valueOf(s: String, radix: int): Double +parseDouble(s: String): double +parseDouble (s: String, radix: int): double

java.lang.Comparable +compareTo(o: Object): int

Page 42: Chapter 14 Abstract Classes and Interfaces

42

The Integer Classand the Double Class

Constructors

Class Constants MAX_VALUE, MIN_VALUE

Conversion Methods

Page 43: Chapter 14 Abstract Classes and Interfaces

43

Numeric Wrapper Class Constructors You can construct a wrapper object either from a primitive data type value or from a string representing the numeric value. The constructors for Integer and Double are:

public Integer(int value)

public Integer(String s)

public Double(double value)

public Double(String s)

Page 44: Chapter 14 Abstract Classes and Interfaces

44

Numeric Wrapper Class Constants Each numerical wrapper class has the constants MAX_VALUE and MIN_VALUE.

MAX_VALUE represents the maximum value of the corresponding primitive data type.

For Byte, Short, Integer, and Long, MIN_VALUE represents the minimum byte, short, int, and long values.

For Float and Double, MIN_VALUE represents the minimum positive float and double values.

The maximum integer (2,147,483,647), the minimum positive float (1.4E-45), and the maximum double floating-point number (1.79769313486231570e+308d).

Page 45: Chapter 14 Abstract Classes and Interfaces

45

Conversion MethodsEach numeric wrapper class implements the abstract methods doubleValue, floatValue, intValue, longValue, and shortValue, which are defined in the Number class.

These methods “convert” objects into primitive type values.

Page 46: Chapter 14 Abstract Classes and Interfaces

46

The Static valueOf MethodsThe numeric wrapper classes have a useful class method, valueOf(String s). This method creates a new object initialized to the value represented by the specified string. For example:

 

Double doubleObject = Double.valueOf("12.4");

Integer integerObject = Integer.valueOf("12");

Page 47: Chapter 14 Abstract Classes and Interfaces

47

The Methods for Parsing Strings into Numbers

You have used the parseInt method in the Integer class to parse a numeric string into an int value and the parseDouble method in the Double class to parse a numeric string into a double value. Each numeric wrapper class has two overloaded parsing methods to parse a numeric string into an appropriate numeric value.

Ex:

Integer.parseInt("11", 2); returns 3

Integer.parseInt("1A", 16); returns 26

Page 48: Chapter 14 Abstract Classes and Interfaces

Remember: An Integer is not An int !!An int is a number; an Integer is a pointer that

can reference an object that contains a number.Consider for example:

int a = 1; int b = 1;System.out.println(a == b);

Integer x = 1; Integer y = 1; System.out.println(x == y);

48

Integer x = new Integer(1);Integer y = new Integer(1);System.out.println(x == y);