Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)

Similar presentations


Presentation on theme: "CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)"— Presentation transcript:

1 CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)

2 SortComparableObjects
Generic sort() java.util.Arrays.sort(array) requires that the elements in an array implement the Comparable<E> interface SortComparableObjects Run 2

3 Defining Classes to Implement Comparable
We cannot use sort() to sort an array of Rectangle objects, because Rectangle does not implement Comparable However, we can define a new rectangle class that implements Comparable. The instances of this new class are comparable ComparableRectangle SortRectangles Run 3 3

4 The Cloneable Interface
The Cloneable interface specifies that an object can be cloned A class that implements the Cloneable interface is marked cloneable, and its objects can be cloned using clone() defined in the Object class. clone() returns the copy of an object package java.lang; public interface Cloneable { } Cloneable is a 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 4

5 Example: Cloneable Several classes (e.g., Date, Calendar and ArrayList) 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 5 5

6 Implementing Cloneable Interface
To define a custom class that implements the Cloneable interface, the class must override clone() in Object The following code defines a class named House that implements Cloneable and Comparable House 6 6

7 Shallow vs. Deep Copy House house1 = new House(1, 1750.50);
House house2 = (House)house1.clone(); If object A is copied as object B then if any properties of A are a reference to a memory location, at the end of copying the two objects will be using the same reference. The default clone() makes a shallow copy 7 7

8 Shallow vs. Deep Copy House house1 = new House(1, 1750.50);
House house2 = (House)house1.clone(); Instead of references, if the actual values are copied to a new object then that will be a deep copy. This way the two objects are completely independent. To make a deep copy, we need to override the default clone() 8 8

9 Interfaces vs. Abstract Classes
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 (abstract methods can’t be static) Interface Must be public static final No constructors. An interface cannot be instantiated using the new operator Must be public abstract (abstract methods can’t be static) 9

10 Interfaces All classes share a single root (Object). There is no single root for interfaces A variable of an interface type can reference any instance of the class that implements that interface Sub-interfaces: public interface infB extends infA {…} If c is an instance of Class2, c is also an instance of Object, Class1, Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2 10

11 The Rational Class Rational TestRationalClass Run 11

12 Class Design Guidelines: Coherence
A class should describe a single entity, and all the class operations should logically fit together to support a coherent purpose We can use a class for students, for example, but we should not combine students and staff in the same class, because students and staff are different entities A single entity with many responsibilities should be broken into several classes to separate the responsibilities The classes String, StringBuilder, and StringBuffer all deal with strings, for example, but have different responsibilities: String deals with immutable strings StringBuilder deals with mutable strings StringBuffer is similar to StringBuilder except that it contains synchronized methods that are required for threaded applications

13 Class Design Guidelines: Consistency
Follow standard Java programming style and naming conventions Choose informative names for classes, data fields, and methods Place the data declaration before the constructor and place constructors before methods Make the names consistent. For example, length() returns the size of a String, StringBuilder, or StringBuffer. It would not be consistent if different names were used for this method in these classes Provide a public no-arg constructor for constructing an instance If a class does not support a no-arg constructor, document the reason If no constructors are defined explicitly, a public no-arg constructor with an empty body is assumed Override equals(), hashCode() and toString() defined in the Object class whenever possible

14 Class Design Guidelines: Encapsulation
A class should use the private modifier to hide its data from direct access by clients. This makes the class easy to maintain Provide accessors and mutators only if necessary Example: The Rational class provides accessors for numerator and denominator, but no mutators, because a Rational object is immutable

15 Class Design Guidelines: Clarity
Cohesion, consistency, & encapsulation improve class clarity. A class should also have a clear contract that is easy to explain & understand Users should be able to use classes in many different combinations, orders, and environments. Therefore, design a class that imposes no restrictions on how or when the user can use it allows the user to set properties in any order and with any combination of values executes methods correctly independent of their order of occurrence Methods should be defined intuitively without causing confusion Example: It is more intuitive to return a substring from beginIndex to endIndex, instead of beginIndex to endIndex-1) Do not declare a data field that can be derived from other data fields (e.g. no need to store both birthdate and age)

16 Class Design Guidelines: Completeness
Classes are designed for use by many different customers. In order to be useful in a wide range of applications, a class should provide a variety of ways for customization through properties and methods Example: The String class contains more than 40 methods that are useful for a variety of applications

17 Class Design Guidelines: Instance vs. static
A variable or method that is dependent on a specific instance of the class must be an instance variable or method A variable that is shared by all the instances of a class should be declared static A method that is not dependent on a specific instance should be defined as a static method Always reference static variables and methods from a class name to improve readability and avoid errors A static variable or method can be invoked from an instance method, but an instance variable or method cannot be invoked from a static method

18 Class Design Guidelines: Inheritance vs. Aggregation
The difference between inheritance and aggregation is the difference between an is-a and a has-a relationship An apple is a fruit; thus, we would use inheritance to model the relationship between the classes Apple and Fruit A person has a name; thus, we would use aggregation to model the relationship between the classes Person and Name

19 Class Design Guidelines: Interfaces vs. Abstract Classes
Both can be used to specify common behavior. In general, a strong is-a relationship that clearly describes a parent-child relationship should be modeled using classes, e.g. orange is a fruit A weak is-a (or is-kind-of ) relationship, indicates that an object possesses a certain property. A weak is-a relationship can be modeled using interfaces, e.g. all strings are comparable, so the String class implements the Comparable interface A circle or a rectangle is a geometric object, so Circle can be designed as a subclass of GeometricObject. Circles are different and comparable based on their radii, so Circle can implement the Comparable interface A subclass can extend only one superclass but can implement any number of interfaces

20 Class Design Guidelines: Visibility Modifiers
Each class can present two contracts – one for the users of the class and one for the extenders of the class The contract for the extenders includes the contract for the users Make the fields private and accessor methods public if they are intended for the users of the class Make the fields or methods protected if they are intended for extenders of the class The extended class may increase the visibility of an instance method from protected to public, or change its implementation, but we should never change the implementation in a way that violates the contract


Download ppt "CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)"

Similar presentations


Ads by Google