Chapter 13 Abstract Classes and Interfaces 1
Abstract Classes Abstraction is to extract common behaviors/properties into a higher level in the class hierarch so that they are shared (implemented) by subclasses as needed. An abstract class may contain abstract methods (methods with no implementation) so that subclasses can implement these methods to meet their difference needs (behaviors). A concrete subclass that extends an abstract class MUST implement all inherited abstract methods, even if they are not used in the subclass. 2
Example: 3
Abstract Class Notes An abstract class cannot be instantiated using the new operator. An abstract class can define constructors (protected visibility), which are invoked in the constructors of its subclasses. An abstract class may contain concrete methods. A subclass can be abstract even if its superclass is concrete (e.g., class Object is concrete!). A subclass can override a method from its superclass to define it abstract. In this case, the subclass MUST be defined abstract. An abstract class can be used as a data type. For example, creating an array of the abstract class GeometricObjects: GeometricObject[] geo = new GeometricObject[10]; 4
Example: Date and Calendar Classes An instance of java.util.date represents a specific instant in time with millisecond precision. java.util.calendar is an abstract base class for extracting information such as year, month, date, hour, minute and second from a Date object. Subclasses of Calendar can implement specific calendar systems such as Gregorian calendar, Lunar Calendar, and Jewish calendar. The Gregorian calendar in implemented in Java (java.util.gregoriancalendar). 5
The get() Method in Class Calendar Method get(int field) defined in class Calendar is useful to extract the date and time information from a Calendar object. The fields are defined as constants, as shown in the following. 6
Gregorian Calendar Subclass Currently, java.util.gregoriancalendar for the Gregorian calendar is supported in the Java API. 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. HW: Type, compile, and run program TestCalendar, page 504, Listing 13.6. 7
Abstract Calendar Class and Its GregorianCalendar Subclass 8
Interfaces An interface is similar to an abstract class, it contains only constants and abstract methods. Interfaces specify common behavior for objects, such as specifying whether objects are comparable, edible, cloneable, etc. Abstract classes used with (strong) is-a relationships; while interfaces used with (weak or is-kind-of) is-a relationships. class Townhouse extends House class Townhouse extends House implements AirConditioning class Chicken extends Animal class Chicken extends Animal implements edible 9
Interface Notes A class may implement more than one Interface classes. Interfaces used to accommodate Multiple Inheritance. Interfaces are used when no revision of behavior is needed. An interface is treated like class. Each interface is compiled into a separate bytecode file. Like an abstract class, you cannot create an instance from an interface using the new operator. In interface is used like abstract class, you can use an interface as a data type for a variable, as the result of casting, and so on. 10
Define an Interface To distinguish an interface from a class, Java uses the following syntax to define an interface: public interface InterfaceName { constant declarations; abstract method signatures; Example: public interface Edible { // describe how to eat public abstract String howtoeat(); 11
Example You can use the Edible interface to specify whether an object is edible. This is done by allowing the class of that object implement this interface. For example, the classes Chicken and Fruit implement interface edible (See TestEdible, page 506). 12
Omitting Modifiers in Interfaces All data fields are public final static and all methods are public abstract in an interface. Thus, these modifiers can be omitted, as shown below: public interface T1 { public static final int K = 1; Equivalent public interface T1 { int K = 1; public abstract void p(); void p(); A constant defined in an interface can be accessed using syntax InterfaceName.CONSTANT_NAME (e.g., T1.K). 13
Interface Comparable // This interface is defined in java.lang package java.lang; public interface Comparable<E> { public int compareto(e o); Note: Since all the numeric wrapper classes (Double, Float, Long, Integer, Short, Byte, BigInteger, BigDecimal) and the Character class implement interface Comparable, the compareto() method is already implemented in these classes. 14
Example: Classes Integer and BigInteger public class Integer extends Number implements Comparable<Integer> { // class body omitted public class BigInteger extends Number implements Comparable<BigInteger> { // class body omitted @Override public int compareto(integer o) { // Implementation omitted @Override public int compareto(biginteger o) { // Implementation omitted Examples: Classes String and Date public class String extends Object implements Comparable<String> { // class body omitted public class Date extends Object implements Comparable<Date> { // class body omitted @Override public int compareto(string o) { // Implementation omitted @Override public int compareto(date o) { // Implementation omitted 15
Import java.util.date;... Code Examples System.out.println(new Integer(3).compareTo(new Integer(5))); //output is -1 System.out.println("ABC".compareTo("ABE")); //output is -2 date1 = new Date(2017, 1, 1); date2 = new Date(2016, 1, 1); System.out.println(date1.compareTo(date2)); //output is 1 Note: The method returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this object is greater than, equal to, or less than the passed object. 16
User-Defined Class to Implement Comparable Note: How you compare 2 objects is a problem-specific. Comparing 2 cars is different than comparing 2 apples, or 2 chairs, or 2 persons, etc. 17
public class ComparableRectangle extends Rectangle implements Comparable<ComparableRectangle> { //Construct a ComparableRectangle with specified properties public ComparableRectangle(double width, double height) { super(width, height); @Override //Implement method compareto() public int compareto(comparablerectangle o) { if (getarea() > o.getarea()) return 1; else if (getarea() < o.getarea()) return -1; else return 0; @Override //Implement method tostring() public String tostring() { return super.tostring() + " Area: " + getarea(); 18
Interface Cloneable It is called Marker Interface, An empty interface. A marker interface does not contain constants or methods. It is used to denote that a class possesses certain desirable properties. A class that implements interface Cloneable is marked cloneable, and its objects can be cloned using the clone() method defined in class Object. package java.lang; public interface Cloneable { Note: The cloned object has its own memory space. 19
Code Example 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 GregorianCalendar(2003, 2, 1); Calendar calendarcopy = (Calendar)calendar.clone(); System.out.println("calendar == calendarcopy is " + (calendar == calendarcopy)); System.out.println("calendar.equals(calendarCopy) is " + calendar.equals(calendarcopy)); displays calendar == calendarcopy is false calendar.equals(calendarcopy) is true 20
Implementing Interface Cloneable To define a custom class that implements interface Cloneable, the class must override method clone() in class Object. Class House implements Cloneable and Comparable. See partial code next slide. See full code page 515, Listing 13.11. 21
public class House implements Cloneable, Comparable<House> { // variables and methods declaration @Override //Override method clone from class Object public Object clone() { try { return super.clone(); catch (CloneNotSupportedException ex) { return null; @Override //Implement method compareto()from Comparable public int compareto(house o) { if (area > o.area) return 1; else if (area < o.area) return -1; else return 0; 22
Shallow vs. Deep Copy House house1 = new House(1, 1750.50); House house2 = (House)house1.clone(); Shallow Copy (by default) 23
Shallow vs. Deep Copy House house1 = new House(1, 1750.50); House house2 = (House)house1.clone(); Deep Copy (customized) See code next slide. See full code page 514-516. 24
Shallow Copy: @Override //Override method clone from class Object public Object clone() { try { return super.clone(); //shallow copy catch (CloneNotSupportedException ex) { return "Object cannot be cloned!"; Deep Copy: @Override //Override method clone from class Object public Object clone() { try { House houseclone = (House)super.clone();//shallow copy //deep copy on Date object whenbuilt houseclone.whenbuilt = (Date)(whenBuilt.clone()); return houseclone; catch (CloneNotSupportedException ex) { return "Object cannot be cloned!"; 25
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. 26
Interfaces vs. Abstract Classes If c is an instance of Class2, Then c is also an instance of classes Object, Class1, Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2. 27
Visibility Modifiers - Revisited Each class can present two contracts: - one for the users of the class - one for the extenders (subclasses) of the class Make the data fields private and the accessor methods (getters and setters) public if they are intended for the users of the class. Make the data fields and methods protected if they are intended for extenders (subclasses) of the class. A class should use the private modifier to hide its data from direct access by clients (users). Use get() and set() methods to provide users with access to only private data that you want the user to see and/or modify. 28
Instance vs. Static - Revisited Instance variable means that each object of the class has its own copy of variables. Instance method means that the method is invoked on the objects (objectname.methodname()). Static variable means that all objects share that one variable. Static method means that the method is invoked on the class (classname.methodname()). Note: a static method or variable can be invoked from an instance method, but an instance variable or method cannot be invoked from a static method! 29
Inheritance vs. Aggregation - Revisited Inheritance implements is-a relationship. E.g., Orange is-a Fruit Class Orange inherits from class Fruit Aggregation implements has-a relationship. E.g., Staff has-a Name Class Staff aggregates (uses) class Name 30
Class Design Hints Coherence: A class describes a single entity. All data fields and operations should logically fit together to support that entity. Do not combine entities into one class, we should not combine students and staff in the same class, because they are different. Separating responsibilities: A single entity with too many responsibilities can be broken into several classes. For example, Java defines classes String and StringBuilder to deal with strings. Each has different responsibilities - String deals with immutable strings; while StringBuilder deals with mutable strings. Reuse: Design for reuse. A class should not imposes no restrictions on what or when the user can do with it. Methods should function independently of their order of occurrence. Users should be able to set properties in any order, with any combination of values. 31
Class Design Hints Consistency: Follow Java programming style and naming conventions. Use informative names for classes, variables, and methods. Always place the data declaration before the constructor, and place constructors before methods. Always provide a constructor and initialize variables to avoid programming errors. Employ Encapsulation and utilize getters and setters as needed. Provide a public no-arg constructor and override methods equals and tostring defined in class Object whenever possible. 32
End of Slides 33