Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Chapter 14 Abstract Classes and Interfaces 1

2 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

3 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.

4 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

5 5 Abstract Classes and Abstract Methods

6 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; }

7 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); }

8 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); }

9 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

10 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()); }

11 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

12 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.

13 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.

14 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.

15 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.

16 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.

17 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();

18 18 The Abstract Calendar Class and Its GregorianCalendar subclass

19 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.

20 20 The GregorianCalendar Class You 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.

21 21 The get Method in Calendar Class The 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.

22 Example Calendar 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, 2012 Calendar calendar1 = new GregorianCalendar(2012, 15, 3); 22

23 Interfaces What is an interface? Why is an interface useful? How do you define an interface? How do you use an interface? 23

24 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.

25 25 Define an Interface To 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(); }

26 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.

27 27 Example You 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).

28 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.

29 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"; }

30 30 Omitting Modifiers in Interfaces All 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: A constant defined in an interface can be accessed using syntax InterfaceName.CONSTANT_NAME (e.g., T1.K).

31 31 Interfaces vs. Abstract Classes In 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. VariablesConstructorsMethods Abstract class No restrictionsConstructors are invoked by subclasses through constructor chaining. An abstract class cannot be instantiated using the new operator. No restrictions. InterfaceAll 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

32 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.

33 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

34 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.

35 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.

36 Interface vs. Inheritance The 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

37 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

38 38 Wrapper Classes Boolean Character Short Byte Integer Long Float Double 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.

39 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.

40 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.

41 41 The Integer and Double Classes

42 42 The Integer Class and the Double Class Constructors Class Constants MAX_VALUE, MIN_VALUE Conversion Methods

43 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)

44 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 ( e+308d).

45 45 Conversion Methods Each 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.

46 46 The Static valueOf Methods The 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");

47 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

48 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);


Download ppt "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."

Similar presentations


Ads by Google