csci1302

38
Abstract Class Abstract Class & & Interface Interface Instructor: Wenjia Li Instructor: Wenjia Li 1 06/28/22

Upload: usernamefire

Post on 26-Jan-2016

213 views

Category:

Documents


0 download

DESCRIPTION

lecture

TRANSCRIPT

Page 1: CSCI1302

Abstract Class Abstract Class & &

InterfaceInterface

Instructor: Wenjia LiInstructor: Wenjia Li

104/21/23

Page 2: CSCI1302

Still Remember Inheritance?Still Remember Inheritance?

04/21/23 2

Page 3: CSCI1302

samePaysamePay Method Method

• Suppose that we decide that it will often be necessary to determine if two Employees have the same pay. – We decide to implement a method named samePay in the Employee

class. – This method should be able to compare the pays for any kinds of

Employees.

04/21/23 3

Page 4: CSCI1302

ProblemProblem with samePay with samePay • The method samePay calls getPay.

– While getPay is defined for SalariedEmployees and HourlyEmployees, there is no meaningful implementation of getPay for a generic Employee.

– We can’t implement getPay without knowing the type of Employee.

• Solution: – Require that classes derived from Employee (who know what type

they are) implement a suitable getPay method that can then be used from samePay.

– Java provides this capability through the use of abstract methods.

04/21/23 4

Page 5: CSCI1302

Abstract Method → Abstract Class Abstract Method → Abstract Class • An abstract method is like a placeholder for a method that

will be fully defined in a descendent class. – It postpones the definition of a method. – It has a complete method heading to which the modifier abstract has

been added. – It cannot be private. – It has no method body, and ends with a semicolon in place of its body.

– The body of the method is defined in the derived classes.

• The class that contains an abstract method is called an abstract class.

04/21/23 5

Page 6: CSCI1302

Abstract ClassAbstract Class• If a class has at least one abstract method, it must be

declared as an abstract class. – Note that a class that has NO abstract methods may also

be declared as abstract, if desired. For example, a class that contains only instance variables.)

• An abstract class must have the modifier abstract included in its class heading.

04/21/23 6

Page 7: CSCI1302

Abstract Class V.S. Concrete ClassAbstract Class V.S. Concrete Class

• An abstract class can have any number of abstract and/or fully defined methods.

• If a derived class of an abstract class adds to or does not define all of the abstract methods, – it is abstract also, and – must add abstract to its modifier AS WELL.

• A class that is not abstract is called a concrete class.

04/21/23 7

Page 8: CSCI1302

AbstractAbstract Employee Class Employee Class

04/21/23 8

Page 9: CSCI1302

Pitfall: You Cannot Create Instances of an Pitfall: You Cannot Create Instances of an Abstract Class Abstract Class

• An abstract class can only be used to derive more specialized classes. – While it may be useful to discuss employees in general, in

reality an employee must be a salaried worker or an hourly worker.

• An abstract class constructor cannot be used to create an object of the abstract class. – However, a derived class constructor will include an

invocation of the abstract class constructor in the form of super.

04/21/23 9

Page 10: CSCI1302

An Abstract Class Is a Type An Abstract Class Is a Type

• Although an object of an abstract class cannot be created, it is perfectly fine to have a parameter of an abstract class type. – This makes it possible to plug in an object of any

of its descendent classes.

• It is also fine to use a variable of an abstract class type, as long is it names objects of its concrete descendent classes only.

04/21/23 10

Page 11: CSCI1302

More Example: CalendarMore Example: Calendar

04/21/23 11

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 12: CSCI1302

CalendarCalendar Class Class

• 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 detailed 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.

• Currently, java.util.GregorianCalendar for the Gregorian calendar is supported in the Java API.

04/21/23 12

Page 13: CSCI1302

The The GregorianCalendarGregorianCalendar Class Class

• Use new GregorianCalendar() to construct a default GregorianCalendar with the current time

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

04/21/23 13

Page 14: CSCI1302

The The getget Method in Calendar Class 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

04/21/23 14

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 15: CSCI1302

InterfacesInterfaces

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

04/21/23 15

Page 16: CSCI1302

What is an What is an interfaceinterface??

• An interface is a classlike 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.– For example, you can specify that the objects are

comparable, edible, cloneable using appropriate interfaces.

04/21/23 16

Page 17: CSCI1302

Omitting Modifiers in InterfacesOmitting 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).

04/21/23 17

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

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

Page 18: CSCI1302

Public InterfacePublic Interface

• Objects define their interaction with the outside world through the their public interface

• A class' public interface is the set of public

members that a user can access – Public non-static members & methods – Public static members & methods

04/21/23 18

Page 19: CSCI1302

Java InterfaceJava Interface

• Interfaces in Java are a set of behaviors that are common to multiple classes.

• The implementation of an Interface is similar to a class, except that interfaces: – Use the keyword interface instead of class – Can only contain public methods, variables, and

constants – Methods do not contain a body. – All methods are implicitly abstract.

04/21/23 19

Page 20: CSCI1302

Define an InterfaceDefine an Interface

• To distinguish an interface from a class, Java uses the following syntax to define an interface:

• Example:

04/21/23 20

public interface InterfaceName { constant declarations; method signatures;}

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

Page 21: CSCI1302

An ExampleAn Example• For instance all Vehicles should be able to – Speed up – Slow down – Turn

04/21/23 21

Page 22: CSCI1302

Some observationsSome observations

• Each method defined in the interface does not have a body.

• Interfaces can only have initialized variables. • Any class that has the same methods defined

in the interface may implement Drivable.

04/21/23 22

Page 23: CSCI1302

ImplementingImplementing Interfaces Interfaces

• A class that uses an interface must – Use the keyword implements – Define all methods that are part of the interface

04/21/23 23

Page 24: CSCI1302

A Closer Look at Interfaces A Closer Look at Interfaces • All methods are implicitly abstract. – A class that implements an interface must

implement all methods defined in the interface in order to be concrete.

– A class that does not implement all methods must be labeled as abstract when appropriate.

• Interfaces can be used as a reference variable type. – All of the rules of polymorphism apply.

04/21/23 24

Page 25: CSCI1302

Example: Comparable Example: Comparable

• Comparable is an interface defined in the Java API that is used to provide an ordering of objects of the same type.

• A class that implements comparable must define the compareTo() method.

• When invoked, a.compareTo(b) returns – a negative number if a < b – 0 if a == b – a positive number if a > b

04/21/23 25

Page 26: CSCI1302

ComparableComparable

04/21/23 26

// This interface is defined in // java.lang packagepackage java.lang;

public interface Comparable { public int compareTo(Object o);}

Page 27: CSCI1302

An Example of ComparableAn Example of Comparable

• Here, we are alphabetically ordering cars by their make and then their model.

04/21/23 27

+

Page 28: CSCI1302

Conventions Conventions • All interface methods must have thorough javadoc

comments. These must include the intended purpose of the method.

• compareTo is supposed to return specific values when invoked. This is a convention of the interface and is enforced by the Java compiler. – The following implementation is syntactically correct, but

violates the intended usage.

04/21/23 28

Page 29: CSCI1302

StringString and and DateDate Classes Classes• Many classes (e.g., String and Date) in the Java library implement

Comparable to define a natural order for the objects. If you examine the source code of these classes, you will see the keyword implements used in the classes, as shown below:

04/21/23 29

public class String extends Object implements Comparable { // class body omitted

}

public class Date extends Object implements Comparable { // class body omitted

}

new String() instanceof Stringnew String() instanceof Comparablenew java.util.Date() instanceof java.util.Datenew java.util.Date() instanceof Comparable

Page 30: CSCI1302

Generic Generic maxmax Method Method

• The return value from the max method is of the Comparable type. So, you need to cast it to String or Date explicitly

04/21/23 30

// Max.java: Find a maximum object public class Max { /** Return the maximum of two objects */ public static Object max (Object o1, Object o2) { if (((Comparable)o1).compareTo(o2) > 0) return o1; else return o2; } }

(a)

// Max.java: Find a maximum object public class Max { /** Return the maximum of two objects */ public static Comparable max (Comparable o1, Comparable o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } }

(b)

String s1 = "abcdef"; String s2 = "abcdee"; String s3 = (String)Max.max(s1, s2);

Date d1 = new Date(); Date d2 = new Date(); Date d3 = (Date)Max.max(d1, d2);

Page 31: CSCI1302

The The CloneableCloneable Interfaces Interfaces

• 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 the Cloneable interface is marked cloneable, and its objects can be cloned using the clone() method defined in the Object class.

04/21/23 31

package java.lang;

public interface Cloneable {

}

Page 32: CSCI1302

Interfaces V. S. Abstract ClassesInterfaces V. S. 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.

04/21/23 32

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 33: CSCI1302

Interfaces V. S. Abstract Classes (Cont.)Interfaces V. S. Abstract Classes (Cont.)

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.

04/21/23 33

Object Class1

Interface1 Interface1_1

Interface1_2

Class2

Interface2_1

Interface2_2

Page 34: CSCI1302

Interface Hierarchy Interface Hierarchy

• Interfaces can be used as the base “class” of other interfaces. – You can derive an interface from another interface using

the keyword extends. – A derived interface inherits all the methods of the base

interface. – To implement a derived interface, all methods must be

implemented by the class.

• Since interfaces can be used as reference variables, they can add to class hierarchies.

04/21/23 34

Page 35: CSCI1302

Class HierarchyClass Hierarchy

04/21/23 35

Page 36: CSCI1302

Multiple Inheritance Multiple Inheritance

• Java does NOT support multiple inheritance with classes. – You can not say Class X extends X, Y

• However, Java does allow a class to implement multiple interfaces.

04/21/23 36

Page 37: CSCI1302

Multiple Interfaces Multiple Interfaces

• The class Liger must implement all methods in both Lion and Tiger.

• Liger can now be referenced by either Lion or Tiger, but is limited to the interface defined in Lion or Tiger, respectively.

04/21/23 37

Page 38: CSCI1302

Multiple Interfaces Multiple Interfaces

• No Java syntax errors will occur for methods that “overlap” from Lion and Tiger. – But in languages like C++, many problems arise from a

“Diamond of Death”.

04/21/23 38