Chapter 13 Abstract Classes and Interfaces Liang Introduction
Chapter 13 Abstract Classes and Interfaces Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 1
Motivations q You can use the java. util. Arrays. sort method to sort an array of numbers or strings. q Can you apply the same sort method to sort an array of geometric objects? q In order to write such code, you have to know about interfaces. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 2
Motivations q A superclass defines common behavior for related subclasses. q An interface can be used to define common behavior for classes (including unrelated classes). q Before discussing interfaces, we introduce a closely related subject: abstract classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 3
Objectives q q q q q To design and use abstract classes (§ 13. 2). To generalize numeric wrapper classes, Big. Integer, and Big. Decimal using the abstract Number class (§ 13. 3). To process a calendar using the Calendar and Gregorian. Calendar classes (§ 13. 4). To specify common behavior for objects using interfaces (§ 13. 5). To define interfaces and define classes that implement interfaces (§ 13. 5). To define a natural order using the Comparable interface (§ 13. 6). To make objects cloneable using the Cloneable interface (§ 13. 7). To explore the similarities and differences among concrete classes, abstract classes, and interfaces (§ 13. 8). To design the Rational class for processing rational numbers (§ 13. 9). To design classes that follow the class-design guidelines (§ 13. 10). Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 4
Abstract Classes and Abstract Methods Geometric. Object Circle Rectangle Test. Geometric. Object Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 5
Geometric. Object class 1 public abstract class Geometric. Object { 2 private String color = "white"; 3 private boolean filled; 4 private java. util. Date date. Created; 5 6 /** Construct a default geometric object */ 7 protected Geometric. Object() { 8 date. Created = new java. util. Date(); 9 } 10 11 /** Construct a geometric object with color and filled value */ 12 protected Geometric. Object(String color, boolean filled) { 13 date. Created = new java. util. Date(); 14 this. color = color; 15 this. filled = filled; 16 } 17 18 /** Return color */ 19 public String get. Color() { 20 return color; 21 } 22 23 /** Set a new color */ 24 public void set. Color(String color) { 25 this. color = color; 26 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 6
Geometric. Object class cont. 28 /** Return filled. Since filled is boolean, 29 * the get method is named is. Filled */ 30 public boolean is. Filled() { 31 return filled; 32 } 33 34 /** Set a new filled */ 35 public void set. Filled(boolean filled) { 36 this. filled = filled; 37 } 38 39 /** Get date. Created */ 40 public java. util. Date get. Date. Created() { 41 return date. Created; 42 } 43 44 @Override 45 public String to. String() { 46 return "created on " + date. Created + "ncolor: " + color + 47 " and filled: " + filled; 48 } 49 50 /** Abstract method get. Area */ 51 public abstract double get. Area(); 52 53 /** Abstract method get. Perimeter */ 54 public abstract double get. Perimeter(); 55 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 7
1 public class Circle extends Geometric. Object { 2 private double radius; 3 4 public Circle() { 5 } 6 7 public Circle(double radius) { 8 this. radius = radius; 9 } 10 11 /** Return radius */ 12 public double get. Radius() { 13 return radius; 14 } 15 16 /** Set a new radius */ 17 public void set. Radius(double radius) { 18 this. radius = radius; 19 } Circle class Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 8
Circle class cont. 21 @Override /** Return area */ 22 public double get. Area() { 23 return radius * Math. PI; 24 } 25 26 /** Return diameter */ 27 public double get. Diameter() { 28 return 2 * radius; 29 } 30 31 @Override /** Return perimeter */ 32 public double get. Perimeter() { 33 return 2 * radius * Math. PI; 34 } 35 36 /* Print the circle info */ 37 public void print. Circle() { 38 System. out. println("The circle is created " + get. Date. Created() + 39 " and the radius is " + radius); 40 } 41 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 9
1 public class Rectangle extends Geometric. Object { 2 private double width; 3 private double height; 4 Rectangle 5 public Rectangle() { 6 } 7 8 public Rectangle(double width, double height) { 9 this. width = width; 10 this. height = height; 11 } 12 13 /** Return width */ 14 public double get. Width() { 15 return width; 16 } 17 18 /** Set a new width */ 19 public void set. Width(double width) { 20 this. width = width; 21 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. class 10
23 /** Return height */ Rectangle 24 public double get. Height() { 25 return height; 26 } 27 28 /** Set a new height */ 29 public void set. Height(double height) { 30 this. height = height; 31 } 32 33 @Override /** Return area */ 34 public double get. Area() { 35 return width * height; 36 } 37 38 @Override /** Return perimeter */ 39 public double get. Perimeter() { 40 return 2 * (width + height); 41 } 42 } class cont. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 11
Why Abstract Methods? Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 12
1 public class Test. Geometric. Object { 2 /** Main method */ 3 public static void main(String[] args) { 4 // Declare and initialize two geometric objects 5 Geometric. Object geo. Object 1 = new Circle(5); 6 Geometric. Object geo. Object 2 = new Rectangle(5, 3); 7 8 System. out. println("The two objects have the same area? " + 9 equal. Area(geo. Object 1, geo. Object 2)); 10 11 // Display circle 12 display. Geometric. Object(geo. Object 1); 13 14 // Display rectangle 15 display. Geometric. Object(geo. Object 2); 16 } 17 18 /** A method for comparing the areas of two geometric objects */ 19 public static boolean equal. Area(Geometric. Object object 1, 20 Geometric. Object object 2) { 21 return object 1. get. Area() == object 2. get. Area(); 22 } 23 24 /** A method for displaying a geometric object */ 25 public static void display. Geometric. Object(Geometric. Object object) { 26 System. out. println(); 27 System. out. println("The area is " + object. get. Area()); 28 System. out. println("The perimeter is " + object. get. Perimeter()); 29 } 30 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 13
The two objects have the same area? false The area is 78. 53981633974483 The perimeter is 31. 41592653589793 The area is 15. 0 The perimeter is 16. 0 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 14
abstract method in abstract class q An abstract method cannot be contained in a nonabstract class. q If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be defined abstract. q In other words, in a nonabstract subclass extended from an abstract class, all the abstract methods must be implemented, even if they are not used in the subclass. q Also note abstract methods are nonstatic. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 15
object cannot be created from abstract class q 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. q For instance, the constructors of Geometric. Object are invoked in the Circle class and the Rectangle class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 16
abstract class without abstract method q A class that contains abstract methods must be abstract. q However, it is possible to define an abstract class that contains no abstract methods. q 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. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 17
superclass of abstract class may be concrete q A subclass can be abstract even if its superclass is concrete. q For example, the Object class is concrete, but its subclasses, such as Geometric. Object, may be abstract. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 18
concrete method overridden to be abstract q A subclass can override a method from its superclass to define it abstract. q This is rare, but useful when the implementation of the method in the superclass becomes invalid in the subclass. q In this case, the subclass must be defined abstract. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 19
abstract class as type q You cannot create an instance from an abstract class using the new operator q but an abstract class can be used as a data type. q Therefore, the following statement, which creates an array whose elements are of Geometric. Object type, is correct. Geometric. Object[] objects = new Geometric. Object[10]; q You can then create an instance of Geometric. Object and assign its reference to the array like this: objects[0] = new Circle(); Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 20
Case Study: the Abstract Number Class Largest. Numbers Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. Run 21
1 import java. util. Array. List; 2 import java. math. *; 3 4 public class Largest. Numbers { 5 public static void main(String[] args) { 6 Array. List<Number> list = new Array. List<>(); 7 list. add(45); // Add an integer 8 list. add(3445. 53); // Add a double 9 // Add a Big. Integer 10 list. add(new Big. Integer("3432323234344343101")); 11 // Add a Big. Decimal 12 list. add(new Big. Decimal("2. 090989091343433344343")); 13 14 System. out. println("The largest number is " + 15 get. Largest. Number(list)); 16 } 17 18 public static Number get. Largest. Number(Array. List<Number> list) { 19 if (list == null || list. size() == 0) 20 return null; 21 22 Number number = list. get(0); 23 for (int i = 1; i < list. size(); i++) 24 if (number. double. Value() < list. get(i). double. Value()) 25 number = list. get(i); 26 27 return number; 28 } 29 } The largest number is 3432323234344343101 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 22
The Abstract Calendar Class and Its Gregorian. Calendar subclass Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 23
The Abstract Calendar Class and Its Gregorian. Calendar subclass An instance of java. util. Date represents a specific instant in time with millisecond precision. q java. util. Calendar is an abstract base class for extracting detailed information such as year, month, date, hour, minute and second from a Date object. q Subclasses of Calendar can implement specific calendar systems such as Gregorian calendar, Lunar Calendar and Jewish calendar. q Currently, java. util. Gregorian. Calendar for the Gregorian calendar is supported in the Java API. q Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 24
The Gregorian. Calendar Class q You can use new Gregorian. Calendar() to construct a default Gregorian. Calendar with the current time. q Use new Gregorian. Calendar(year, month, date) to construct a Gregorian. Calendar with the specified year, month, and date. q The month parameter is 0 -based, i. e. , 0 is for January. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 25
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. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 26
Getting Date/Time Information from Calendar Test. Calendar Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 27
1 import java. util. *; 2 3 public class Test. Calendar { 4 public static void main(String[] args) { 5 // Construct a Gregorian calendar for the current date and time 6 Calendar calendar = new Gregorian. Calendar(); 7 System. out. println("Current time is " + new Date()); 8 System. out. println("YEAR: " + calendar. get(Calendar. YEAR)); 9 System. out. println("MONTH: " + calendar. get(Calendar. MONTH)); 10 System. out. println("DATE: " + calendar. get(Calendar. DATE)); 11 System. out. println("HOUR: " + calendar. get(Calendar. HOUR)); 12 System. out. println("HOUR_OF_DAY: " + 13 calendar. get(Calendar. HOUR_OF_DAY)); 14 System. out. println("MINUTE: " + calendar. get(Calendar. MINUTE)); 15 System. out. println("SECOND: " + calendar. get(Calendar. SECOND)); 16 System. out. println("DAY_OF_WEEK: " + 17 calendar. get(Calendar. DAY_OF_WEEK)); 18 System. out. println("DAY_OF_MONTH: " + 19 calendar. get(Calendar. DAY_OF_MONTH)); 20 System. out. println("DAY_OF_YEAR: " + 21 calendar. get(Calendar. DAY_OF_YEAR)); 22 System. out. println("WEEK_OF_MONTH: " + 23 calendar. get(Calendar. WEEK_OF_MONTH)); 24 System. out. println("WEEK_OF_YEAR: " + 25 calendar. get(Calendar. WEEK_OF_YEAR)); 26 System. out. println("AM_PM: " + calendar. get(Calendar. AM_PM)); } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 28
28 // Construct a calendar for December 25, 1997 29 Calendar calendar 1 = new Gregorian. Calendar(1997, 11, 25); 30 String[] day. Name. Of. Week = {"Sunday", "Monday", "Tuesday", "Wednesday", 31 "Thursday", "Friday", "Saturday"}; 32 System. out. println("December 25, 1997 is a " + 33 day. Name. Of. Week[calendar 1. get(Calendar. DAY_OF_WEEK) - 1]); 34 } 35 } Current time is Fri Mar 15 21: 48: 01 IST 2019 YEAR: 2019 MONTH: 2 DATE: 15 HOUR: 9 HOUR_OF_DAY: 21 MINUTE: 48 SECOND: 1 DAY_OF_WEEK: 6 DAY_OF_MONTH: 15 DAY_OF_YEAR: 74 WEEK_OF_MONTH: 3 WEEK_OF_YEAR: 11 AM_PM: 1 December 25, 1997 is a Thursday Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 29
Interfaces What is an interface? Why is an interface useful? How do you define an interface? How do you use an interface? Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 30
What is an interface? Why is an interface useful? q An interface is a class like construct that contains only constants and abstract methods. q In many ways, an interface is similar to an abstract class. q. Its intent is to specify common behavior for objects of related classes or unrelated classes q For example, you can specify that the objects are comparable, edible, cloneable using appropriate interfaces. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 31
Define an Interface To distinguish an interface from a class, Java uses the following syntax to define an interface: public interface Interface. Name { constant declarations; abstract method signatures; } Example: public interface Edible { /** Describe how to eat */ public abstract String how. To. Eat(); } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 32
Interface is a Special Class q An interface is treated like a special class in Java. q Each interface is compiled into a separate bytecode file, just like a regular class. q Like an abstract class, you cannot create an instance from an interface using the new operator. q In most cases you can use an interface more or less the same way you use an abstract class. q For example, you can use an interface as a data type for a variable, as the result of casting, and so on. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 33
Example q You can now use the Edible interface to specify whether an object is edible. q This is accomplished by letting the class for the object implement this interface using the implements keyword. q For example, the classes Chicken and Fruit implement the Edible interface (See Test. Edible). q When a class implements an interface, it implements all the methods defined in the interface. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 34
Example cont. Edible Test. Edible Run 35 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.
15 abstract class Animal { 16 private double weight; 17 18 public double get. Weight() { 19 return weight; 20 } 21 22 public void set. Weight(double weight) { 23 this. weight = weight; 24 } 25 26 /** Return animal sound */ 27 public abstract String sound(); 28 } 29 30 class Chicken extends Animal implements Edible { 31 @Override 32 public String how. To. Eat() { 33 return "Chicken: Fry it"; 34 } 35 36 @Override 37 public String sound() { 38 return "Chicken: cock-a-doodle-doo"; 39 } 40 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 36
42 class Tiger extends Animal { 43 @Override 44 public String sound() { 45 return "Tiger: RROOAARR"; 46 } 47 } 48 49 abstract class Fruit implements Edible { 50 // Data fields, constructors, and methods omitted here 51 } 52 53 class Apple extends Fruit { 54 @Override 55 public String how. To. Eat() { 56 return "Apple: Make apple cider"; 57 } 58 } 59 60 class Orange extends Fruit { 61 @Override 62 public String how. To. Eat() { 63 return "Orange: Make orange juice"; 64 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All 65 } 37 rights reserved.
1 public class Test. Edible { 2 public static void main(String[] args) { 3 Object[] objects = {new Tiger(), new Chicken(), new Apple()}; 4 for (int i = 0; i < objects. length; i++) { 5 if (objects[i] instanceof Edible) 6 System. out. println(((Edible)objects[i]). how. To. Eat()); 7 8 if (objects[i] instanceof Animal) { 9 System. out. println(((Animal)objects[i]). sound()); 10 } 11 } 12 } 13 } public interface Edible { /** Describe how to eat */ public abstract String how. To. Eat(); } Tiger: RROOAARR Chicken: Fry it Chicken: cock-a-doodle-doo Apple: Make apple cider Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 38
Omitting Modifiers in Interfaces q All data fields are public final static and all methods are public abstract in an interface. q For this reason, these modifiers can be omitted, as shown below: q The method must be defined public when it is implemented in a subclass (e. g. void p()) q A constant defined in an interface can be accessed using syntax Interface. Name. CONSTANT_NAME q (e. g. , T 1. K). Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 39
Which of the following is a correct interface? interface A { void print() { } } abstract interface A { abstract void print() { } } (a) (b) (c) abstract interface A { print(); } (d) interface A { void print(); } Show the error in the following code: interface A { void m 1(); } class B implements A { void m 1() { System. out. println("m 1"); } } interface A { (e) default void print() { } } (f) interface A { static int get() { return 0; } } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 40
Example: The Comparable Interface The Comparable interface defines the compare. To method for comparing objects. // This interface is defined in // java. lang package java. lang; public interface Comparable<E> { public int compare. To(E o); } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 41
Example: The Comparable Interface q Suppose you want to design a generic method to find the larger of two objects of the same type, q two students, two dates, two circles, two rectangles, or two squares. q In order to accomplish this, the two objects must be comparable, so the common behavior for the objects must be comparable Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 42
The to. String, equals, and hash. Code Methods q Each wrapper class overrides the to. String, equals, and hash. Code methods defined in the Object class. q Since all the numeric wrapper classes and the Character class implement the Comparable interface, the compare. To method is implemented in these classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 43
Integer and Big. Integer Classes String and Date Classes Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 44
Example 1 System. out. println(new Integer(3). compare. To(new Integer(5))); 2 System. out. println("ABC". compare. To("ABE")); 3 java. util. Date date 1 = new java. util. Date(2013, 1, 1); 4 java. util. Date date 2 = new java. util. Date(2012, 1, 1); 5 System. out. println(date 1. compare. To(date 2)); − 1 0 1 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 45
Generic sort Method Let n be an Integer object, s be a String object, and d be a Date object. All the following expressions are true. q The java. util. Arrays. sort(array) method q Requires that the elements in an array are instances of Comparable<E>. q Uses the compare. To method to compare and sorts the objects in an array Provided the objects are instances of the Comparable interface. Sort. Comparable. Objects Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. Run 46
1 import java. math. *; 2 3 public class Sort. Comparable. Objects { 4 public static void main(String[] args) { 5 String[] cities = {"Savannah", "Boston", "Atlanta", "Tampa"}; 6 java. util. Arrays. sort(cities); 7 for (String city: cities) 8 System. out. print(city + " "); 9 System. out. println(); 10 11 Big. Integer[] huge. Numbers = {new Big. Integer("2323231092923992"), 12 new Big. Integer("43223239292"), 13 new Big. Integer("54623239292")}; 14 java. util. Arrays. sort(huge. Numbers); 15 for (Big. Integer number: huge. Numbers) 16 System. out. print(number + " "); 17 } 18 } Atlanta Boston Savannah Tampa 54623239292 43223239292 2323231092923992 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 47
Defining Classes to Implement Comparable. Rectangle Sort. Rectangles Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. Run 48
1 public class Comparable. Rectangle extends Rectangle 2 implements Comparable<Comparable. Rectangle> { 3 /** Construct a Comparable. Rectangle with specified properties */ 4 public Comparable. Rectangle(double width, double height) { 5 super(width, height); 6 } 7 8 @Override // Implement the compare. To method defined in Comparable 9 public int compare. To(Comparable. Rectangle o) { 10 if (get. Area() > o. get. Area()) 11 return 1; 12 else if (get. Area() < o. get. Area()) 13 return -1; 14 else 15 return 0; 16 } 17 18 @Override // Implement the to. String method in Geometric. Object 19 public String to. String() { 20 return "Width: " + get. Width() + " Height: " + get. Height() + 21 " Area: " + get. Area(); 22 } 23 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 49
1 public class Sort. Rectangles { 2 public static void main(String[] args) { 3 Comparable. Rectangle[] rectangles = { 4 new Comparable. Rectangle(3. 4, 5. 4), 5 new Comparable. Rectangle(13. 24, 55. 4), 6 new Comparable. Rectangle(7. 4, 35. 4), 7 new Comparable. Rectangle(1. 4, 25. 4)}; 8 java. util. Arrays. sort(rectangles); 9 for (Rectangle rectangle: rectangles) { 10 System. out. print(rectangle + " "); 11 System. out. println(); 12 } 13 } 14 } Width: 3. 4 Height: 5. 4 Area: 18. 36 Width: 1. 4 Height: 25. 4 Area: 35. 559999995 Width: 7. 4 Height: 35. 4 Area: 261. 96 Width: 13. 24 Height: 55. 4 Area: 733. 496 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 50
Interface is another form of generic q An interface provides another form of generic programming. q It would be difficult to use a generic sort method to sort the objects without using an interface in this example q Using multiple inheritance would be necessary to inherit Comparable and another class, such as Rectangle, at the same time. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 51
Implementing Multiple Interfaces public class My. Interface. Impl implements My. Interface, My. Other. Interface { public void say. Hello() { System. out. println("Hello"); } public void say. Goodbye() { System. out. println("Goodbye"); } } Interfaces and Inheritance public interface My. Super. Interface { public void sai. Hello(); } public interface My. Sub. Interface extends My. Super. Interface { public void say. Goodbye(); } As when implementing multiple interfaces, there are no rules for how you handle the situation when multiple superinterfaces have methods with the same signature Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 52
The Cloneable Interfaces q The Cloneable interface specifies that an object can be cloned. q Marker Interface: An empty interface. package java. lang; public interface Cloneable { } q A marker interface does not contain constants or methods. q It is used to denote that a class possesses certain desirable properties. q A class that implements the Cloneable interface is marked cloneable, and its objects can be cloned using the clone() method defined in the Object class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 53
Examples Many classes (e. g. , Date and Calendar) in the Java library implement Cloneable. Thus, the instances of these classes can be cloned. For example, the following code Calendar calendar = new Gregorian. Calendar(2003, 2, 1); Calendar calendar. Copy = (Calendar)calendar. clone(); System. out. println("calendar == calendar. Copy is " + (calendar == calendar. Copy)); System. out. println("calendar. equals(calendar. Copy) is " + calendar. equals(calendar. Copy)); displays calendar == calendar. Copy is false calendar. equals(calendar. Copy) is true Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 54
Header of clone Method q The header of clone method defined in the Object class is protected native Object clone() throws Clone. Not. Supported. Exception; q The keyword native indicates that this method is not written in Java, but is implemented in the JVM for the native platform q The keyword protected restricts the method to be accessed in the same package or in a subclass q The clone method implemented for the native platform in the Object class performs the task of cloning objects Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 55
The Java Native Interface (JNI) is a framework that allows your Java code to call native applications and libraries written in languages such as C, C++ and Objective-C Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 56
Implementing Cloneable Interface q To define a custom class that implements the Cloneable interface, the class must override the clone() method in the Object class. q The following code defines a class named House that implements Cloneable and Comparable. q clone method in the House class simply invokes super. clone(). House Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 57
1 public class House implements Cloneable, Comparable<House> { 2 private int id; 3 private double area; 4 private java. util. Date when. Built; 5 6 public House(int id, double area) { 7 this. id = id; 8 this. area = area; 9 when. Built = new java. util. Date(); 10 } 11 12 public int get. Id() { 13 return id; 14 } 15 16 public double get. Area() { 17 return area; 18 } 19 20 public java. util. Date get. When. Built() { 21 return when. Built; 22 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 58
24 @Override /** Override the protected clone method defined in 25 the Object class, and strengthen its accessibility */ 26 public Object clone() { 27 try { 28 return super. clone(); 29 } 30 catch (Clone. Not. Supported. Exception ex) { 31 return null; 32 } 33 } 34 35 @Override // Implement the compare. To method defined in Comparable 36 public int compare. To(House o) { 37 if (area > o. area) 38 return 1; 39 else if (area < o. area) 40 return -1; 41 else 42 return 0; 43 } 44 } The clone method defined in the Object class throws Clone. Not. Supported. Exception if the object is not a type of Cloneable. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 59
Shallow vs. Deep Copy House house 1 = new House(1, 1750. 50); House house 2 = (House)house 1. clone(); Shallow Copy Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 60
Shallow vs. Deep Copy House house 1 = new House(1, 1750. 50); House house 2 = (House)house 1. clone(); Deep Copy Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 61
Deep Copy public Object clone() throws Clone. Not. Supported. Exception { // Perform a shallow copy House house. Clone = (House)super. clone(); // Deep copy on when. Built house. Clone. when. Built = (java. util. Date)(when. Built. clone()); return house. Clone; } public Object clone() { try { // Perform a shallow copy House house. Clone = (House)super. clone(); // Deep copy on when. Built house. Clone. when. Built = (java. util. Date)(when. Built. clone()); return house. Clone; } catch (Clone. Not. Supported. Exception ex) { return null; } } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 62
Questions q Why is the clone method in the Object class defined protected, not public? q Not every object can be cloned. The designer of Java purposely forces the subclasses to override it if an object of the subclass is cloneable. q Why is the clone method not defined in the Cloneable interface? q Java provides a native method that performs a shallow copy to clone an object. q Since a method in an interface is abstract, this native method cannot be implemented in the interface. The definition and implementation of the native clone method in the Object class. q Why doesn’t the Object class implement the Cloneable Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All interface? rights reserved. 63
Questions q What would happen if the House class did not implement Cloneable in line 1 of Listing 13. 11? q house 1. clone() would return null because super. clone() in line 28 would throw a Clone. Not. Supported. Exception. q You may implement the clone method in the House class without invoking the clone method in the Object class as follows: public Object clone() { // Perform a shallow copy House house. Clone = new House(id, area); // Deep copy on when. Built house. Clone. when. Built = new Date(); house. Clone. get. When. Built(). set. Time(when. Built. get. Time()); return house. Clone; } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 64
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. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 65
Interfaces vs. Abstract Classes, cont. Java allows only single inheritance for class extension, but allows multiple extensions for interfaces. For example, public class New. Class extends Base. Class implements Interface 1, . . . , Interface. N { . . . } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 66
Interfaces vs. Abstract Classes, cont. An interface can inherit other interfaces using the extends keyword. Such an interface is called a subinterface. public interface New. Interface extends Interface 1, . . . , Interface. N { // constants and abstract methods } q A class implementing New. Interface must implement the abstract methods defined in New. Interface, Interface 1, . . . , and Interface. N. q An interface can extend other interfaces, but not classes. q A class can extend its superclass and implement multiple interfaces. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 67
Interfaces vs. Abstract Classes, cont. q All classes share a single root, the Object class, but there is no single root for interfaces. q Like a class, an interface also defines a type. q A variable of an interface type can reference any instance of the class that implements the interface. q If a class extends an interface, this interface plays the same role as a superclass. You can use an interface as a data type and cast a variable of an interface type to its subclass, and vice versa. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 68
Interfaces vs. Abstract Classes, cont. Suppose that c is an instance of Class 2. c is also an instance of Object, Class 1, Interface 1_1, Interface 1_2, Interface 2_1, and Interface 2_2. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 69
Caution: conflict interfaces q In rare occasions, a class may implement two interfaces with conflict information q Examples are two same constants with different values or two methods with same signature but different return type. q This type of errors will be detected by the compiler. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 70
Whether to use an interface or a class? q Abstract classes and interfaces can both be used to model common features. q How do you decide whether to use an interface or a class? q 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. q A weak is-a relationship, also known as an is-kind-of relationship, indicates that an object possesses a certain property. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 71
Whether to use an interface or a class? q A weak is-a relationship can be modeled using interfaces. For example, all strings are comparable, so the String class implements the Comparable interface. q You can also use interfaces to circumvent single inheritance restriction if multiple inheritance is desired. q In the case of multiple inheritance, you have to design one as a superclass, and others as interface. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 72
The Rational Class q A rational number has a numerator and a denominator in the form a/b, where a is the numerator and b the denominator. q A rational number cannot have a denominator of 0, but a numerator of 0 is fine. q Every integer i is equivalent to a rational number i/1. q Rational numbers are used in exact computations involving fractions—for example, 1/3 = 0. 33333. . This number cannot be precisely represented in floating-point format using either the data type double or float. To obtain the exact result, we must use rational numbers. q Java does not provides data types for rational 73 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.
The Rational Class q. Rational numbers share many common features with integers and floating-point numbers. q Number is the root class for numeric wrapper classes, it is appropriate to define Rational as a subclass of Number. q Rational numbers are comparable, the Rational class should also implement the Comparable interface. q. There are many equivalent rational numbers—for example, 1/3 = 2/6 = 3/9 = 4/12. The numerator and the denominator of 1/3 have no common divisor except 1, so 1/3 is said to be in lowest terms. q. Figure 13. 8 illustrates the Rational class and its relationship to the Number class and the Comparable interface. 74 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.
The Rational Class Rational Test. Rational. Class Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. Run 75
1 public class Rational extends Number implements Comparable<Rational> { 2 // Data fields for numerator and denominator 3 private long numerator = 0; 4 private long denominator = 1; 5 6 /** Construct a rational with default properties */ 7 public Rational() { 8 this(0, 1); 9 } 10 11 /** Construct a rational with specified numerator and denominator */ 12 public Rational(long numerator, long denominator) { 13 long gcd = gcd(numerator, denominator); 14 this. numerator = (denominator > 0 ? 1 : -1) * numerator / gcd; 15 this. denominator = Math. abs(denominator) / gcd; 16 } 17 18 /** Find GCD of two numbers */ 19 private static long gcd(long n, long d) { 20 long n 1 = Math. abs(n); 21 long n 2 = Math. abs(d); 22 int gcd = 1; 23 24 for (int k = 1; k <= n 1 && k <= n 2; k++) { 25 if (n 1 % k == 0 && n 2 % k == 0) 26 gcd = k; 27 } 28 29 return gcd; 30 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All 76 rights reserved.
32 /** Return numerator */ 33 public long get. Numerator() { 34 return numerator; 35 } 36 37 /** Return denominator */ 38 public long get. Denominator() { 39 return denominator; 40 } 41 42 /** Add a rational number to this rational */ 43 public Rational add(Rational second. Rational) { 44 long n = numerator * second. Rational. get. Denominator() + 45 denominator * second. Rational. get. Numerator(); 46 long d = denominator * second. Rational. get. Denominator(); 47 return new Rational(n, d); 48 } 49 50 /** Subtract a rational number from this rational */ 51 public Rational subtract(Rational second. Rational) { 52 long n = numerator * second. Rational. get. Denominator() 53 - denominator * second. Rational. get. Numerator(); 54 long d = denominator * second. Rational. get. Denominator(); 55 return new Rational(n, d); 56 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 77
58 /** Multiply a rational number to this rational */ 59 public Rational multiply(Rational second. Rational) { 60 long n = numerator * second. Rational. get. Numerator(); 61 long d = denominator * second. Rational. get. Denominator(); 62 return new Rational(n, d); 63 } 64 65 /** Divide a rational number from this rational */ 66 public Rational divide(Rational second. Rational) { 67 long n = numerator * second. Rational. get. Denominator(); 68 long d = denominator * second. Rational. numerator; 69 return new Rational(n, d); 70 } 71 72 @Override 73 public String to. String() { 74 if (denominator == 1) 75 return numerator + ""; 76 else 77 return numerator + "/" + denominator; 78 } 79 80 @Override // Override the equals method in the Object class 81 public boolean equals(Object other) { 82 if ((this. subtract((Rational)(other))). get. Numerator() == 0) 83 return true; 84 else 85 return false; 86 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 78
88 @Override // Implement the abstract int. Value method in Number 89 public int. Value() { 90 return (int)double. Value(); 91 } 92 93 @Override // Implement the abstract float. Value method in Number 94 public float. Value() { 95 return (float)double. Value(); 96 } 97 98 @Override // Implement the double. Value method in Number 99 public double. Value() { 100 return numerator * 1. 0 / denominator; 101 } 102 103 @Override // Implement the abstract long. Value method in Number 104 public long. Value() { 105 return (long)double. Value(); 106 } 107 108 @Override // Implement the compare. To method in Comparable 109 public int compare. To(Rational o) { 110 if (this. subtract(o). get. Numerator() > 0) 111 return 1; 112 else if (this. subtract(o). get. Numerator() < 0) 113 return -1; 114 else 115 return 0; 116 } 117 } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 79
1 public class Test. Rational. Class { 2 /** Main method */ 3 public static void main(String[] args) { 4 // Create and initialize two rational numbers r 1 and r 2. 5 Rational r 1 = new Rational(4, 2); 6 Rational r 2 = new Rational(2, 3); 7 8 // Display results 9 System. out. println(r 1 + " + r 2 + " = " + r 1. add(r 2)); 10 System. out. println(r 1 + " - " + r 2 + " = " + r 1. subtract(r 2)); 11 System. out. println(r 1 + " * " + r 2 + " = " + r 1. multiply(r 2)); 12 System. out. println(r 1 + " / " + r 2 + " = " + r 1. divide(r 2)); 13 System. out. println(r 2 + " is " + r 2. double. Value()); 14 } 15 } 2 + 2/3 = 8/3 2 – 2/3 = 4/3 2 * 2/3 = 4/3 2 / 2/3 = 3 2/3 is 0. 66666666 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 80
Designing a Class (Coherence) q A class should describe a single entity, and all the class operations should logically fit together to support a coherent purpose. q You can use a class for students, for example, but you should not combine students and staff in the same class, because students and staff have different entities. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 81
Designing a Class, (Coherence) cont. q (Separating responsibilities) A single entity with too many responsibilities can be broken into several classes to separate responsibilities. q The classes String, String. Builder, and String. Buffer all deal with strings, for example, but have different responsibilities. q The String class deals with immutable strings, the String. Builder class is for creating mutable strings, and the String. Buffer class is similar to String. Builder except that String. Buffer contains synchronized methods for updating strings. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 82
Designing a Class, Consistency q Follow standard Java programming style and naming conventions. q Choose informative names for classes, data fields, and methods. q Always place the data declaration before the constructor, and place constructors before methods. q Always provide a constructor and initialize variables to avoid programming errors. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 83
Designing a Class, Consistency cont. q Provide a public no-arg constructor and override the equals method and the to. String method defined in the Object class whenever possible. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 84
Using Visibility Modifiers q Each class can present two contracts – one for the users of the class and one for the extenders of the class. q Make the fields private and accessor methods public if they are intended for the users of the class. q Make the fields or method protected if they are intended for extenders of the class. q The contract for the extenders encompasses the contract for the users. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 85
Using Visibility Modifiers , cont. q The extended class may increase the visibility of an instance method from protected to public, or change its implementation, but you should never change the implementation in a way that violates that contract. q A class should use the private modifier to hide its data from direct access by clients. You can use get methods and set methods to provide users with access to the private data, but only to private data you want the user to see or to modify. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 86
Using Visibility Modifiers, cont. q A class should also hide methods not intended for client use. q The gcd method in the Rational class is private, for example, because it is only for internal use within the class. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 87
Designing a Class, cont. q Classes are designed for reuse. Users can incorporate classes in many different combinations, orders, and environments. q Therefore, you should design a class that imposes no restrictions on what or when the user can do with it q design the properties to ensure that the user can set properties in any order, with any combination of values q design methods to function independently of their order of occurrence. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 88
Using the static Modifier q A property that is shared by all the instances of the class should be declared as a static property. q A variable that is shared by all the instances of a class should be declared static. q A method that is not dependent on a specific instance should be defined as a static method. q For instance, the get. Number. Of. Objects() method in Circle is not tied to any specific instance and therefore is defined as a static method. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. 89
- Slides: 89