CEN 414 Java Programmingenformatik.cu.edu.tr/Java-2/Week4-5-java.pdfSlides are modified from...

39
Slides are modified from original slides of Y. Daniel Liang CEN 414 Java Programming Week 4-5 / Abstract Classes and Interfaces Dr. H. Esin ÜNAL SPRING 2020

Transcript of CEN 414 Java Programmingenformatik.cu.edu.tr/Java-2/Week4-5-java.pdfSlides are modified from...

Slides are modified from original slides of Y. Daniel Liang

CEN 414Java Programming

Week 4-5 / Abstract Classes and Interfaces

Dr. H. Esin ÜNALSPRING

2020

Introduction

A superclass defines common behavior for related

subclasses. An interface can be used to define common

behavior for classes (including unrelated classes).

For instance;

java.util.Arrays.sort method is used to sort an array of

numbers or strings.

You can apply the same sort method to sort an array of

geometric objects by using interfaces.

Before discussing interfaces, we introduce a closely

related subject: abstract classes.

Week 4-5 CEN 414 Java Programming - Spring 2020 2

AbstractClasses

SUPERCLASS

More general

Less specific

SUBCLASS

Concrete

More spesific

Week 4-5 CEN 414 Java Programming - Spring 2020 3

Class design should ensure that a superclass containscommon features of its subclasses.

Sometimes a superclass is so abstract that it cannot beused to create any specific instances. Such a class isreferred to as an abstract class.

AbstractMethods

Week 4-5 CEN 414 Java Programming - Spring 2020 4

GeometricObject was defined as the superclass for Circle and Rectangle.You can compute areas and perimeters for all geometric objects so itwould be better to define them under GeometricObject class.

However, these methodscannot be implementedin the GeometricObjectclass, because theirimplementation dependson the specific type ofgeometric object.

Such methods arereferred to as abstractmethods and aredenoted using theabstract modifier inthe method header.

Abstract Classes

&AbstractMethods

After you define the abstract methods inGeometricObject, it becomes an abstract class. Abstractclasses are denoted using the abstract modifier in theclass header.

Week 4-5 CEN 414 Java Programming - Spring 2020 5

Abstract GeometricObject Class

http://www.cs.armstrong.edu/liang/intro10e/html/GeometricObject.html

Circle Class

http://www.cs.armstrong.edu/liang/intro10e/html/Circle.html

Rectangle Class

http://www.cs.armstrong.edu/liang/intro10e/html/Rectangle.html

Why AbstractMethods?

public class TestGeometricObject {/** Main method */public static void main(String[] args) {// Declare and initialize two geometric objectsGeometricObject geoObject1 = new Circle(5);GeometricObject geoObject2 = new Rectangle(5, 3);

System.out.println("The two objects have the same area? " +equalArea(geoObject1, geoObject2));

// Display circledisplayGeometricObject(geoObject1);

// Display rectangledisplayGeometricObject(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());

}}

Week 4-5 CEN 414 Java Programming - Spring 2020 6

Declared type: GeometricObjectActual type: Circle

Declared type: GeometricObjectActual type: Rectangle

When invoking equalArea(geoObject1,geoObject2), the getArea() method defined in theCircle class is used for object1.getArea(), sincegeoObject1 is a circle, and the getArea() methoddefined in the Rectangle class is used forobject2.getArea(), since geoObject2 is arectangle.

Invoking displayGeometricObject(geoObject1),the methods getArea() and getPerimeter()defined in the Circle class are used, and wheninvoking displayGeometricObject(geoObject2),the methods getArea and getPerimeter defined inthe Rectangle class are used. The JVMdynamically determines which of these methodsto invoke at runtime, depending on the actualobject that invokes the method.

Note that you could not define the equalAreamethod for comparing whether two geometricobjects have the same area if the getAreamethod were not defined in GeometricObject

Interesting

Points

Abstract method in abstract class:An abstract method cannot be contained in a non-abstract

class.

If a subclass of an abstract superclass does not implement allthe abstract methods, the subclass must be defined abstract.

In other words, in a non-abstract subclass extended from anabstract class, all the abstract methods must beimplemented, even if they are not used in the subclass.

Object cannot be created from abstract class:An abstract class cannot be instantiated using the new

operator, but you can still define its constructors, which areinvoked in the constructors of its subclasses.

For instance, the constructors of GeometricObject are invokedin the Circle class and the Rectangle class.

Week 4-5 CEN 414 Java Programming - Spring 2020 7

Interesting

Points

Abstract class without abstract method:A class that contains abstract methods must be abstract.

However, it is possible to define an abstract class thatcontains no abstract methods.

This class is used as a base class for defining a new subclass.

Concrete method overridden to be abstract:A subclass can override a method from its superclass to

define it abstract.

This is rare, but useful when the implementation of themethod in the superclass becomes invalid in the subclass.

In this case, the subclass must be defined abstract.

Week 4-5 CEN 414 Java Programming - Spring 2020 8

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 asGeometricObject, may be abstract.

Abstract class as 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 whoseelements are of GeometricObject type, is correct.

GeometricObject[] geo = new GeometricObject[10];

You can then create an instance of GeometricObject and assign itsreference to the array like this:

geo[0] = new Circle();

Week 4-5 CEN 414 Java Programming - Spring 2020

Interesting

Points

9

Interesting

Points

Abstract methods can not be static:You can't declare a static method to be abstract. Normally,

the compiler can guarantee that an abstract method will havea real implementation any time that it is called, because youcan't create an instance of an abstract class. But since a staticmethod can be called directly, making it abstract would make itpossible to call an undefined method.

abstract class Foo {

abstract static void bar();

}

// Calling a method with no body!

Foo.bar();

Week 4-5 CEN 414 Java Programming - Spring 2020 10

Case Study: The Abstract

NumberClass

Number is an abstract superclass for numeric wrapperclasses, BigInteger, and BigDecimal.

If the doubleValue() method were not defined in the Numberclass, you will not be able to find the largest number amongdifferent types of numbers using the Number class.

Week 4-5 CEN 414 Java Programming - Spring 2020

FINDING LARGEST among DIFFERENT TYPES of NUMBERS

http://www.cs.armstrong.edu/liang/intro10e/html/LargestNumber.html

11

Interface

An interface is a reference type, similar to a class, that can contain

only constants, method signatures for abstract methods, default

methods and static methods.

Method body exist only for default methods and static methods.

The method signatures have no braces and are terminated with a

semicolon (abstract methods) .

Interfaces cannot be instantiated – they can only be implemented

by classes or extended by other interfaces.

When a class implements an interface, it implements all the

methods defined in the interface with the exact signature and

return type.

Week 4-5 CEN 414 Java Programming - Spring 2020 12

Interface is a Special Class

An interface is treated like a special class in Java.

In many ways, an interface is similar to an abstract class, but theintent of an interface is to specify common behavior for objects ofrelated classes or unrelated classes. For example, you can specifythat the objects are comparable, edible and/or cloneable usingappropriate interfaces.

Each interface is compiled into a separate bytecode file, just like aregular class.

Like an abstract class, you cannot create an instance from aninterface using the new operator (it doesn’t have a constructor),but in most cases you can use an interface more or less the sameway you use an abstract class. For example, you can use aninterface as a data type for a variable, as the result of casting, andso on.

Week 4-5 CEN 414 Java Programming - Spring 2020 13

Define an Interface

An interface declaration consists of modifiers, the keywordinterface, the interface name, a comma-seperated listof parent interfaces (if any), and the interface body:

As an example;

modifier interface InterfaceName extends Interface1, Interface2

{

//constant declarations;

//method signatures;

//default or static methods

}

public interface Edible {

/** Describe how to eat */

public abstract String howToEat();

}

Week 4-5 CEN 414 Java Programming - Spring 2020 14

The InterfaceBody

Default methods are defined with the default modifier and staticmethods with the static keyword.

All abstract, default, and static methods in a interface are implicitlypublic, so you can omit the public modifier.

All data fields are public static final and all abstract methodsare implicitly public abstract in an interface. For this reason, thesemodifiers can be omitted, too:

A constant defined in an interface can be accessed using syntaxInterfaceName.CONSTANT_NAME (e.g., T.K).

Week 4-5 CEN 414 Java Programming - Spring 2020 15

Example:Implementingan Interface

You can now use the Edible interface to specify whether an object isedible. This is accomplished by letting the class for the object implementthis interface using the implements keyword. For example, the classesChicken and Fruit implement the Edible interface.

In essence, the Edible interface defines common behavior for edibleobjects. All edible objects have the howToEat method.

Week 4-5 CEN 414 Java Programming - Spring 2020

http://www.cs.armstrong.edu/liang/intro10e/html/TestEdible.html

TEST EDIBLE INTERFACE

16

Example:Implementingan Interface

This example uses several classes and interfaces;1. The Animal class defines the sound method. It is an abstract

method and will be implemented by a concrete animal class.

2. The Chicken class implements Edible to specify that chickensare edible. So, it implements the howToEat method.

3. The Chicken class also extends Animal (an abstract class) toimplement the sound method.

4. The Fruit class implements Edible. Since it does notimplement the howToEat method, Fruit must be denoted asabstract

5. The concrete subclasses of Fruit must implement thehowToEat method. The Apple and Orange classesimplement the howToEat method.

Week 4-5 CEN 414 Java Programming - Spring 2020 17

Using an Interface as a

Type

When you define a new interface, you are defining a newreference data type.

If you define a reference variable whose type is an interface, anyobject you assign to it must be an instance of a class thatimplements the interface.

This method works for any "relatable" objects, no matter whattheir class inheritance is. When they implement Relatable, theycan be of both their own class (or superclass) type and a Relatabletype. This gives them the advantages of multiple inheritance.

Week 4-5 CEN 414 Java Programming - Spring 2020 18

public Object findLargest(Object o1, Object o2) {Relatable obj1=(Relatable)o1;Relatable obj2=(Relatable)o2;if ((obj1).isLargerThan(obj2)>0

return o1;else

return o2; }

Using an Interface as a

Type

All classes share a single root, the Object class, but there is no single root forinterfaces. Like a class, an interface also defines a type. A variable of an interfacetype can reference any instance of the class that implements the interface. If aclass implements 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 toits subclass, and vice versa.

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.

Week 4-5 CEN 414 Java Programming - Spring 2020 19

EvolvingInterfaces

When you want to change an interface, then all classes thatimplement the old interface will break because they no longerimplement the old interface.

If you want to add additional methods to an interface;1. You could create a new interface that extends the old one. So that the

users of your code can choose to continue to use the old or theupgraded one.

2. You could define your new methods as default methods. Remember toprovide an implementation for default methods.

You could also define new static methods to existing interfaces.

Week 4-5 CEN 414 Java Programming - Spring 2020 20

public interface DoIt {int doSome(String s);default boolean didIt(int i,String s){

//method body}

}

The Comparable

Interface

The Comparable interface defines the compareTo method forcomparing objects.

Suppose you want to design a generic method to find thelarger of two objects of the same type, such as two students,two dates, two circles, two rectangles, or two squares. Inorder to accomplish this, the two objects must becomparable, so the common behavior for the objects must becomparable. Java provides the Comparable interface for thispurpose.

The interface is defined as follows:

Week 4-5 CEN 414 Java Programming - Spring 2020

// This interface is defined in java.lang package

package java.lang;

public interface Comparable<E> {public int compareTo(E o);

}

21

The Comparable

Interface

The compareTo method determines the order of this

object with the specified object o and returns a negative

integer, zero, or a positive integer if this object is less

than, equal to, or greater than o.

The Comparable interface is a generic interface. The

generic type E is replaced by a concrete type when

implementing this interface. Many classes in the Java

library implement Comparable to define a natural order

for objects.

Week 4-5 CEN 414 Java Programming - Spring 2020 22

The Comparable

Interface

The classes Byte, Short, Integer, Long, Float, Double,Character, BigInteger, BigDecimal, Calendar, String, andDate all implement the Comparable interface.

Week 4-5 CEN 414 Java Programming - Spring 2020 23

Example

Thus, numbers are comparable, strings are comparable,and so are dates.

displays:-1

-2

1

System.out.println(new Integer(3).compareTo(new Integer(5)));

System.out.println("ABC".compareTo("ABE"));

java.util.Date date1 = new java.util.Date(2013, 1, 1);

java.util.Date date2 = new java.util.Date(2012, 1, 1);

System.out.println(date1.compareTo(date2));

Week 4-5 CEN 414 Java Programming - Spring 2020 24

Generic sortMethod

Let n be an Integer object, s be a String object, and d be aDate object. All the following expressions are true.

Since all Comparable objects have the compareTomethod, the java.util.Arrays.sort(Object[]) method inthe Java API uses the compareTo method to compareand sorts the objects in an array, provided that theobjects are instances of the Comparable interface.

Week 4-5 CEN 414 Java Programming - Spring 2020

http://www.cs.armstrong.edu/liang/intro10e/html/SortComparableObjects.html

SORT COMPARABLE OBJECTS

25

Defining Classes to

Implement Comparable

ComparableRectangle extends Rectangle and implements Comparable.

The keyword implements indicates that ComparableRectangle inheritsall the constants from the Comparable interface and implements themethods in the interface.

The compareTo method compares the areas of two rectangles.

An instance of ComparableRectangle is also an instance of Rectangle,GeometricObject, Object, and Comparable.

Week 4-5 CEN 414 Java Programming - Spring 2020

http://www.cs.armstrong.edu/liang/intro10e/html/ComparableRectangle.html

COMPARABLE RECTANGLE

http://www.cs.armstrong.edu/liang/intro10e/html/SortRectangles.html

SORT RECTANGLES

26

The Cloneable

Interfaces

The Cloneable interface specifies that an object can be cloned.

This interface is empty. An interface with an empty body isreferred to as a marker interface.

A marker interface does not contain constants or methods. It isused to denote that a class possesses certain desirableproperties. A class that implements the Cloneable interface ismarked cloneable, and its objects can be cloned using theclone() method defined in the Object class.

Week 4-5 CEN 414 Java Programming - Spring 2020 27

// This interface is defined in java.lang package

package java.lang;

public interface Cloneable {}

Example

Many classes (e.g., Date and Calendar) in the Java library implementCloneable. Thus, the instances of these classes can be cloned. Forexample, the following code;

Calendar calendar = new GregorianCalendar(2003, 2, 1);

Calendar calendar1 = calendar;

Calendar calendar2 = (Calendar)calendar.clone();

System.out.println("calendar == calendar1 is " +

(calendar == calendar1));

System.out.println("calendar == calendar2 is " +

(calendar == calendar2));

System.out.println("calendar.equals(calendar2) is " +

calendar.equals(calendar2));

displays:calendar == calendar1 is true

calendar == calendar2 is false

calendar.equals(calendar2) is true

Week 4-5 CEN 414 Java Programming - Spring 2020 28

Defining Classes to

Implement Cloneable

To define a custom class that implements the Cloneable

interface, the class must override the clone() method in

the Object class.

The example code defines a class named House that

implements Cloneable and Comparable.

Week 4-5 CEN 414 Java Programming - Spring 2020

http://www.cs.armstrong.edu/liang/intro10e/html/House.html

HOUSE CLASS

29

Interfaces vs. Abstract Classes

Abstract classes are similar to interfaces. You cannot instantiatethem, and they may contain a mix of methods declared with orwithout an implementation.

However,

1. With abstract classes, you can declare fields that are not staticand final, and define public, protected, and private concretemethods. With interfaces, all fields are automatically public,static, and final (i.e. constant), and all methods that you declareor define (as default methods) are public.

2. You can extend only one class, whether or not it is abstract,whereas you can implement any number of interfaces.

3. Interfaces give you more flexibility than classes, because youdon’t have to make everything fit into one type of class (as inEdible interface).

Week 4-5 CEN 414 Java Programming - Spring 2020 30

Whether to use an

interface or a class?

Abstract classes and interfaces can both be used to modelcommon features.

In general, a strong is-a relationship that clearly describes aparent-child relationship should be modeled using classes. Forexample, a staff member is a person.

A weak is-a relationship, also known as an is-kind-of relationship,indicates that an object possesses a certain property. A weak is-arelationship can be modeled using interfaces.

For example, all strings are comparable, so the String class implementsthe Comparable interface.

You can also use interfaces to circumvent single inheritancerestriction if multiple inheritance is desired. In the case ofmultiple inheritance, you have to design one as a superclass, andothers as interface.

Week 4-5 CEN 414 Java Programming - Spring 2020 31

Interfaceor

Abstract class

Consider using abstract classes if any of these statements apply toyour situation: You want to share code among several closely related classes.

You expect that classes that extend your abstract class have manycommon methods or fields, or require access modifiers other than public(such as protected and private).

You want to declare non-static or non-final fields. This enables you todefine methods that can access and modify the state of the object towhich they belong.

Consider using interfaces if any of these statements apply to yoursituation:

You expect that unrelated classes would implement your interface. Forexample, the interfaces Comparable and Cloneable are implemented bymany unrelated classes.

You want to specify the behavior of a particular data type, but notconcerned about who implements its behavior.

You want to take advantage of multiple inheritance of type.

Week 4-5 CEN 414 Java Programming - Spring 2020 32

Class DesignGuidelines

Coherence

A class should describe a single entity, and all the classoperations should logically fit together to support acoherent purpose.

You can use a class for students, for example, but youshould not combine students and staff in the same class,because students and staff have different entities.

A single entity with many responsibilities can be brokeninto several classes to separate the responsibilities. Theclasses String, StringBuilder, and StringBuffer all dealwith strings, for example, but have differentresponsibilities.

Week 4-5 CEN 414 Java Programming - Spring 2020 33

Class DesignGuidelines

Consistency

Follow standard Java programming style and namingconventions.

Choose informative names for classes, data fields, andmethods.

Always place the data declaration before the constructor,and place constructors before methods.

Always provide a constructor and initialize variables toavoid programming errors.

Provide a public no-arg constructor and override theequals method and the toString method defined in theObject class whenever possible.

Week 4-5 CEN 414 Java Programming - Spring 2020 34

Class DesignGuidelines

Encapsulation

A class should use the private modifier to hide its datafrom direct access by clients.

You can use get methods and set methods to provideusers with access to the private data, but only to privatedata you want the user to see or to modify.

A class should also hide methods not intended for clientuse.

Week 4-5 CEN 414 Java Programming - Spring 2020 35

For example, the gcd method in the Rational class is private, because it is only for internal use within the class.

Class DesignGuidelines

Clarity

A class should have a clear contract that is easy to explainand easy to understand

Classes are designed for reuse. Users can incorporateclasses in many different combinations, orders, andenvironments.

Therefore, you should design a class that imposes norestrictions on what or when the user can do with it,design the properties to ensure that the user can setproperties in any order, with any combination of values,and design methods to function independently of theirorder of occurrence.

Week 4-5 CEN 414 Java Programming - Spring 2020 36

For example, the Loan class contains the properties loanAmount, numberOfYears, and annualInterestRate. The values of these

properties can be set in any order.

Class DesignGuidelines

Staticvs

Instance

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.

Always reference static variables and methods from a

class name (rather than a reference variable) to improve

readability and avoid errors.

Week 4-5 CEN 414 Java Programming - Spring 2020 37

Class DesignGuidelines

Staticvs

Instance

Do not pass a parameter from a constructor to initialize a

static data field. It is better to use a setter method to

change the static data field.

Week 4-5 CEN 414 Java Programming - Spring 2020 38

Class DesignGuidelinesInterfaces

vsAbstract Classes

A weak is-a relationship can be modeled using interfaces

A strong is-a relationship that clearly describes a parent–child relationship should be modeled using classes

Both interfaces and abstract classes can be used tospecify common behavior for objects.

Interfaces are more flexible than abstract classes,because a subclass can extend only one superclass butcan implement any number of interfaces.

Week 4-5 CEN 414 Java Programming - Spring 2020 39