Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 15 Abstract Classes and Interfaces

Similar presentations


Presentation on theme: "Chapter 15 Abstract Classes and Interfaces"— Presentation transcript:

1 Chapter 15 Abstract Classes and Interfaces
Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

2 Introduction Abstract Classes
A superclass defines common behavior for related subclasses. An interface can be used to define common behavior for classes (including unrelated classes). Abstract Classes An abstract class cannot be used to create objects. An abstract class can contain abstract methods, which are implemented in concrete subclasses.

3 Abstract Classes and Abstract Methods
3

4 1 public abstract class GeometricObject {
28 /** Return filled. Since filled is boolean, 29 * the get method is named isFilled */ 30 public boolean isFilled() { 31 return filled; 32 } 33 34 /** Set a new filled */ 35 public void setFilled(boolean filled) { 36 this.filled = filled; 37 } 38 39 /** Get dateCreated */ 40 public java.util.Date getDateCreated() { LISTING 15.1 GeometricObject.java 1 public abstract class GeometricObject { 2 private String color = "white"; 3 private boolean filled; 4 private java.util.Date dateCreated; 5 6 /** Construct a default geometric object */ 7 protected GeometricObject() { 8 dateCreated = new java.util.Date(); 9 } 10 11 /** Construct a geometric object with color and filled */ 12 protected GeometricObject(String color, boolean filled) { 13 dateCreated = new java.util.Date(); 14 this.color = color; 15 this.filled = filled; 16 } 17 18 /** Return color */ 19 public String getColor() { 20 return color; 21 } 22 23 /** Set a new color */ 24 public void setColor(String color) { 25 this.color = color; 26 } 27 41 return dateCreated; 42 } 43 45 public String toString() { 46 return "created on " + dateCreated + "\ncolor: " + color + 47 " and filled: " + filled; 48 } 49 50 /** Abstract method getArea */ 51 public abstract double getArea( ); 52 53 /** Abstract method getPerimeter */ 54 public abstract double getPerimeter ( ); 55 }

5 LISTING 15.2 Circle.java public classCircle extends GeometricObject { // Same as lines in Listing 11.2, so omitted public double getArea( ) { return radius * radius * Math.PI; } public double getPerimeter() { return 2 * radius * Math.PI; LISTING 15.3 Rectangle.java public class Rectangle extends GeometricObject { // Same as lines in Listing 11.3, so omitted public double getArea() { return width * height; return 2 * (width + height);

6 LISTING 15.4 TestGeometricObject.java
1 public class TestGeometricObject { 2 /** Main method */ 3 public static void main(String[] args) { 4 // Create two geometric objects 5 6 GeometricObject geoObject2 = new Rectangle(5, 3); 7 GeometricObject geoObject1 = new Circle(5); 8 System.out.println("The two objects have the same area? " + equalArea(geoObject1, geoObject2)); 9 10 11 // Display circle 12 displayGeometricObject(geoObject1); 13 14 // Display rectangle 15 displayGeometricObject(geoObject2); 16 } 17 18 /** A method for comparing the areas of two geometric objects */ 19 public static boolean equalArea(GeometricObject object1, GeometricObject object2) { 20 21 return object1.getArea() == object2.getArea(); 22 }

7 LISTING 15.4 TestGeometricObject.java, cont.
23 24 /** A method for displaying a geometric object */ 25 public static void displayGeometricObject(GeometricObject object) { 26 System.out.println( ); 27 System.out.println("The area is " + object.getArea( )); 28 System.out.println("The perimeter is " + object.getPerimeter( )); 29 } 30 } 7

8 abstract method in abstract class
An abstract method cannot be contained in a nonabstract class. If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be defined abstract. 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. 8

9 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 are invoked in the constructors of its subclasses. For instance, the constructors of GeometricObject are invoked in the Circle class and the Rectangle class. 9

10 abstract class without abstract method
A class that contains abstract methods must be abstract. However, it is possible to define an abstract class that contains no abstract methods. 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. 10

11 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 as GeometricObject, may be abstract. 11

12 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 the method in the superclass becomes invalid in the subclass. In this case, the subclass must be defined abstract. 12

13 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 whose elements are of GeometricObject type, is correct. GeometricObject[] geo = new GeometricObject[10]; 13

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

15 What is an interface? Why is an interface useful?
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 its intent is to specify common behavior for objects of related classes or unrelated classes. 15

16 Define an Interface Example:
To distinguish an interface from a class, Java uses the following syntax to define an interface: public interface InterfaceName { constant declarations; method signatures; } Example: public interface Edible { /** Describe how to eat */ public abstract String howToEat(); } 16

17 Interface is a Special Class
An interface is treated like a special class in Java. Each interface is compiled into a separate bytecode file, just like a regular class. Like an abstract class, you cannot create an instance from an interface using the new operator, but in most cases you can use an interface more or less the same way you use an abstract class. For example, you can use an interface as a data type for a variable, as the result of casting, and so on. 17

18 Example You can now use the Edible interface to specify whether an object is edible. This is accomplished by letting the class for the object implement this interface using the implements keyword. For example, the classes Chicken and Fruit implement the Edible interface (See TestEdible).

19

20 LISTING 15.7 TestEdible.java
1 public class TestEdible { 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]).howToEat( )); 7 8 if (objects[i] instanceof Animal) { 9 System.out.println(((Animal)objects[i]).sound( )); 10 } 11 } 12 } 13 } 14 15 abstract class Animal { 16 /** Return animal sound */ 17 public abstract String sound(); 18 } 19

21 LISTING 15.7 TestEdible.java, cont.
20 class Chicken extends Animal implements Edible { 22 public String howToEat( ) { 23 return "Chicken_eat"; 24 } 25 27 public String sound( ) { 28 return "Chicken_sound"; 29 } 30 } 31 32 class Tiger extends Animal { 34 public String sound( ) { 35 return "Tiger_sound"; 36 } 37 }

22 LISTING 15.7 TestEdible.java, cont.
38 39 abstract class Fruit implements Edible { 40 // Data fields, constructors, and methods omitted here 41 } 42 43 class Apple extends Fruit { 45 public String howToEat( ) { 46 return "Apple_eat"; 47 } 48 } 49 50 class Orange extends Fruit { 52 public String howToEat( ) { 53 return "Orange_eat"; 54 } 55 }

23 Omitting 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). 23

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

25 Interfaces vs. Abstract Classes, cont.
All classes share a single root, the Object class, but there is no single root for interfaces. Like a class, an interface also defines a type. A variable of an interface type can reference any instance of the class that implements the interface. 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. 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. 25

26 Caution: conflict interfaces
In rare occasions, a class may implement two interfaces with conflict information (e.g., two same constants with different values or two methods with same signature but different return type). This type of errors will be detected by the compiler.

27 Whether to use an interface or a class?
Abstract classes and interfaces can both be used to model common features. How do you decide whether to use an interface or a class? 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. So their relationship should be modeled using class inheritance. A weak is-a relationship, also known as an is-kind-of relationship, indicates that an object possesses a certain property. A weak is-a relationship can be modeled using interfaces. For example, all strings are comparable, so the String class implements the Comparable interface. You can also use interfaces to circumvent single inheritance restriction if multiple inheritance is desired. In the case of multiple inheritance, you have to design one as a superclass, and others as interface


Download ppt "Chapter 15 Abstract Classes and Interfaces"

Similar presentations


Ads by Google