Abstract Classes and Interfaces

CSC72002
Object Oriented Programming
Topic 2
Abstract Classes and Interfaces
©
Southern Cross University
Developed and produced by Southern Cross University
Military Rd, EAST LISMORE. N.S.W. 2480. 2nd Session, 2018.
No part of this publication may be reproduced, stored in a retrieval system or transmitted
in any form of by means electronic, mechanical, photocopying, recording or otherwise
without the prior written permission of the publisher.
Copyright materials reproduced herein are used under the provisions of the
Copyright Amendment Act (1989).
Readings, if any, indicated in this work have been copied under section VB of the Copyright Amendment Act 1989
Copies, if any, were made by Southern Cross University in 2018
for private study only by students.
CAL LICENSED COPY – UNAUTHORISED COPYING PROHIBITED
CSC72002 Study Guide
2-3
Contents
ABSTRACT CLASSES AND INTERFACES …………………………………………………………………………………………….4
References……………………………………………………………………………………………………………………………………………..4
Objectives………………………………………………………………………………………………………………………………………………4
Introduction……………………………………………………………………………………………………………………………………………4
Abstract classes ………………………………………………………………………………………………………………………………………4
Interfaces……………………………………………………………………………………………………………………………………………….6
Java provided abstract classes and interfaces ………………………………………………………………………………………………9
Summary ……………………………………………………………………………………………………………………………………………..12
CSC72002 Study Guide Abstract classes and interfaces
2-4
Abstract classes and interfaces
References
Liang, Y.D. 2015. Introduction to Java Programming – Comprehensive Version, 10th Edition, Pearson,
USA. ISBN:978-1-292-07001-8.
Objectives
On completion of this topic you should be able to:
1. Declare abstract classes
2. Use abstract classes in inheritance hierarchies
3. Declare interfaces
4. Implement interfaces
5. Use interfaces in inheritance hierarchies
Introduction
Abstract classes are class that cannot be used to create new objects. Their purpose is to provide a
placeholder and partial implementation details for use in an inheritance hierarchy. When you first see
abstract classes, it is not immediately obvious why we would want to use one. To understand this, you
must consider the code re-use attribute of object-oriented programming. When a programmer creates
code for other people to re-use, an abstract class provide a base class that forces other programmer to
implement compatible methods. This will make sense when we see some examples, but keep in mind
an abstract class is usually implemented for others to use in an inheritance hierarchy.
An interface is the ultimate abstract class, where there are no implementation details given and only
signatures of methods are provided. The fact that no implementation code is given means that a given
class can use multiple interfaces as base classes. A special term is given to using a interfaces as a
abstract base class. We say a class implements one or more interfaces. This makes sense because a
interface contains no implementation code and the class that uses it as a base class must implement the
code for all the method signatures contained in the interface.
In this topic we will first exam abstract classes and then look at interfaces.
Abstract classes
We will explain abstract classes by using a simple example that is a simplified version of the example
from the textbook. Suppose we wished to implement a class of object to represent shapes. Two such
shapes could be a square and a rectangle. We can define all the attributes of shapes in general in a class
and then re-use this in specific classes derived from this. This will make it possible to implement other
derived classes later. A simple implementation of a shape class using concepts you have seen previously
is as follows.
public class Shape
private final int shapeID;
public Shape(int id)
shapeID = id;

CSC72002 Study Guide Abstract classes and interfaces
2-5
Now this class can be used as a base class for the following concrete shape classes.
public class Square extends Shape
private final double side;
public Square(int id, double side)
super(id);
this.side = side;

YOU MAY ALSO READ ...  HOMEWORK PROBLEM

public double area()
return side * side;

public class Rectangle extends Shape
private final double side1;
private final double side2;
public Rectangle(int id, double side1, double side2)
super(id);
this.side1 = side1;
this.side2 = side2;

public double area()
return side1 * side2;

Note this technique, as we have seen before, allows the code for the Shape class to be re-used.
However, it has two main limitations:
1. Objects of the Shape class can be created but it is unlikely we would want that to happen. The
only purpose of the shape class is to provide reusable code for the Square and Rectangle classes.
2. Both the derived classes implement an area() method that calculates the area of the shape. It
would be nice to force all similar derived classes to implement this method but there is no obvious
way to do this. If an area() method was implemented in the Shape base class a derived class
may just inherit the method or forget about it entirely. The inherited method would almost certainly
incorrectly calculate the area of the shape in these cases.
The following abstract class implementation of the Shape class solves both these issues. Take note of
the two occurrences of the keyword abstract.
public abstract class Shape
private final int shapeID;
protected Shape(int id)
this.shapeID = id;

public abstract double area();

The keyword abstract in the class header signals that no instances of this class can ever be created.
The placement of abstract in the area() method header signifies that this method must be
implemented in all derived classes. Notice how this abstract method is just a method signature and has
no body. You should also note that the constructor in the abstract class is protected. Since we cannot
create concrete objects using an abstract class there will be no new operation to call the constructor but
the derived classes will need to use this inherited constructor.
So why is this useful? First, it solves the two problems with the non-abstract base class described above.
Since no objects of type Shape can now be created we do not have to worry about accidentally creating
one. It also now has the compiler force any derived classes to implement the area() method. This
means that we can use polymorphism as we discussed in the previous Topic. As an example, suppose
CSC72002 Study Guide Abstract classes and interfaces
2-6
we wanted to implement a method to print out the area of any shape on the console. We can implement
this method, possibly in the abstract class, as follows.
public void printArea(Shape s)
System.out.println(“The area is “+s.area());

Notice that we have the abstract base class in the method signature, even though we cannot create
instances of Shape objects. This provides the same polymorphic processing as we saw in the standard
inheritance hierarchy in the previous Topic.
UML also has specific syntax for abstract classes and methods. For abstract classes the class name is
in italic font. For an abstract method the method description is also in italic font. So, for example, the
above class relationships can be models as shown in Figure x.1.
Figure x.1 – UML diagram of abstract class and inheritance
In addition to the technical differences between a normal base class and an abstract base class, we should
keep in mind the re-use aspect mentioned in the introduction to this topic. If a class is designed for
another programmer to use, the ability to force the implementation of methods in a derived class has
many advantages. The main one being that the developer of the abstract class can also write methods
that will process the other programmer’s objects using the polymorphic processing allowed by Java.
This means that a collection of abstract classes, normal classes and other Java objects can be distributed
to other programmers as a package. This is exactly how the Java API is provided for all programmers
and other organisations provide other specialised packages for use by other programmers.

YOU MAY ALSO READ ...  We can help on: Model Research
 Activity 2-1: Abstract classes
1. Read the textbook Section 13.2 (pp 518-523)
2. Implement the above Shape, Square and Rectangle classes and the polymorphic
printArea() function. If you implement it in mainline class, don’t forget the
static keyword. Test the function by creating some Square and Rectangle
objects as shown above.
3. Implement another derived class called Circle. Note that the area of a circle can be
calculated as Math.PI*(radius*radius). This is similar to the Circle class in
the reading.

Next, we look at interfaces.
Interfaces
An interface is really an abstract class that has all abstract methods. Once you have all abstract methods
there are some additional properties that are possessed by interfaces and so Java has a special structure
for their implementation.
We will start discussing interfaces with a simple example. The following is a simple interface
declaration called Danger.
CSC72002 Study Guide Abstract classes and interfaces
2-7
public interface Danger
String danger(); // why is it dangerous

Notice how we have a new keyword interface to declare the interface. Another aspect of interfaces
is that the methods declared in the interface do not have to have any modifiers. This is because all
interface members must be public and abstract. As we have already mentioned, an interface is
really an abstract class with all abstract methods. This means that the keyword abstract is also assumed
in all interfaces. However, public and abstract can be used if you wish. For example, the following
declaration defines precisely the same interface.
public interface Danger
public abstract String danger(); // why is it dangerous

Now we need to see how interfaces are used. The following class called Glass uses the Danger
interface as a base interface. This is termed: “the class Glass implements the Danger interface”.
public class Glass implements Danger
private int length;
private int width;
public Glass(int l, int w)
length = l;
width=w;

@Override
public String danger()
return “glass breaks and is sharp”;

As you can see there is a new keyword implements to show that Danger implements the interface.
You can also see we have implemented the method danger() which is defined in the interface.
We are not restricted to one member function in an interface. We can define any number of methods
as shown in the following example.
public interface Audible
String sound(); // return sound
void newSound(String s); // update sound

YOU MAY ALSO READ ...  Cognitive Neuropsychology

The Audible interface has two member functions. It also shows we can define parameters in our
interface member functions. We can implement this interface in a class to represent pets as follows.
public class Pet implements Audible
private String name;
private String sound;
public Pet(String n, String s)
name = n;
sound=s;

@Override
public String sound()
return name + ” says ” + sound;

@Override
public void newSound(String snd)
sound=snd;

This is a straight forward extension of the previous example. Notice how the parameter name in the
implementation of the newSound() member function is different to the formal parameter defined in
CSC72002 Study Guide Abstract classes and interfaces
2-8
the interface declaration. This is possible because the compiler is really only interested in the type of
the parameters. However usually the same parameter name can be used and this was just to show how
it can be different.
An important feature of interfaces is that a class can implement more than one interface. We can only
extend one class but we can implement any number of interfaces. For example, we can also implement
the Danger interface above in the Pet class as follows.
public class Pet implements Audible, Danger
// same implementation as above
@Override
public String danger()
return “pets can bite you”;

We just list the interfaces separated by commas. Note also that we can extend a base class and
implement interfaces as you will see in the reading below.
To the UML standard an interface is represented no different than an abstract class. However, UML
does allow us to add our own flag (called a stereotype) which allows us to identify Java interfaces as
different to abstract classes. We will adopt the technique used in the textbook and in many other places
to identify interfaces using the <> stereotype. This is important for Java because
interfaces are treated quite different to abstract classes. In addition, UML does provide a different arrow
for interface implementation (as opposed to class extension). This is shown using a dashed line with
the open triangle arrow similar to the class inheritance arrow. Figure x.2 shows the above two interfaces
and the implementation hierarchy.
Figure x.2 – UML interface implementation example
We can also define interfaces with no methods inside them. These are called “tagging” interfaces or
“marker” interfaces. These interfaces are used in the implementation list just to flag that objects of the
class satisfy some requirement other than implementing methods. It is not clear but this can be an
important mechanism for the re-use of APIs. The developer of the API can specify some property that
is flagged by a tagging interface. This means that the programmer who uses the API, by placing the
interface name in the implementation list, has acknowledge the requirement. An example of a tagging
interface is the Java Serializable interface which flags a class of objects of that class can be
serialised (turned into a stream of data) for data transmission. The ability to serialise an object is a
programmer design issue and not a programming issue so it is left to the programmer whether to specify
the tagging interface.
A final attribute of interfaces is that we can also specify attributes that must be implemented in the
classes that implement them. However, there is a restriction, and that is that all attributes implemented
must be public static final. In other words, the interface specifies constants. These are rarely
CSC72002 Study Guide Abstract classes and interfaces
2-9
used. Because all interface attributes must be public static final, these modifiers can be omitted
in an interface definition.

 Activity 2-2: Interfaces
1. Read the textbook Section 13.5 (pp 528-530).
2. Implement the above example Pet class, the example that implements two interfaces.
You will need to add several files to your project, 2 interfaces and two classes. Test
the code by creating instances of the classes and printing the member function results
on the console.
3. Add the following interface to your project from 2:
interface Printable
void print(); // display details on console

Implement this interface in your Pet class and test it. You will just print the Pet
attributes on the console using your own format.

We will now look at some of the Java API abstract classes and interfaces.
Java abstract classes and interfaces
To have a better understand of how abstract classes and interfaces are provided to other programmers
we will look at some of the ones provided in the Java API.
An important Java abstract class is Number. This class is the base class for many wrapper classes you
have used before, e.g. Integer, Double, Float, etc. It is also the base case for some special arithmetic
object, e.g. BigDecimal which is an object to represent unlimited precision decimal numbers. Its
definition is as follows.
public abstract class Number implements java.io.Serializable
public abstract int intValue();
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue();
public byte byteValue() return (byte)intValue();
public short shortValue() return (short)intValue();
private static final long serialVersionUID = -8742448824652078965L;

Notice that Number implements the Serializable interface. Abstract classes can implement interfaces
just as any non-abstract class can. The class also implements concrete methods that, in this case, call
an abstract method. This is not a problem because, when an object is created of a derived class, the
abstract method will be implemented.
Now, one of the subclasses of Number is Integer, a class that you have used previously. This class
implements the abstract methods shown, so the following code is possible.
Number n = new Integer(23);
int x = n.intValue();
long y = n.longValue();
float z = n.floatValue();
double d = n.doubleValue();
Similarly, the Double wrapper class has the same member function implemented. This is an interesting
case because, as you should know, if you extract an integer from a floating-point number the fraction
part will be lost. As an example, suppose we print on the console the results of each of these functions
for a double precision floating point number, e.g.
CSC72002 Study Guide Abstract classes and interfaces
2-10
n = new Double(112.3456789D);
System.out.println(n.intValue());
System.out.println(n.longValue());
System.out.println(n.floatValue());
System.out.println(n.doubleValue());
This would display the following text ion the console:
112
112
112.34568
112.3456789
Here the fraction part is lost in the calls to the intValue() and longValue() implemented functions.
In the third line we also loose the precision of the double-precision number by calling the
floatValue() method. This loss of precision is not a result of the abstract class inheritance, it is just
the result of the implementation restrictions.
Next, we will look at interfaces from the Java API. Unfortunately, most interfaces are declared as
generic types, a subject that we will look at in another Topic. However, there are a few interfaces that
are not generic and you will be able to see how they are used (rather than use them yourself).
In the java.io package there are several simple interfaces that provide important functions. For
example, the Closable interface is used to indicate an I/O stream is closable. This is important because
closing a stream will release system resources that can be re-used by other processes. It’s definition is
similar to the following.
public interface Closeable
void close();

You will see in the reading below that many java.io classes implement this interface.
Similarly, there is another interface called Flushable which is defined similar to the following:
public interface Flushable
void flush();

The flush() operation is important so that buffers in volatile memory may be saved on permanent
storage so they are not lost in system crashes.
The activity below does not ask you to implement any of the Java API interfaces but does ask you to
read the documentation. You will get plenty of experience using the Java API generic interfaces in the
Generics Topic.
CSC72002 Study Guide Abstract classes and interfaces
2-11

 Activity 2-2: Java API abstract classes and interfaces
Read the textbook Section 13.3 (pp. 523-524) which also shows the above example of an
abstract class in a different way.
1. Implement the code shown to verify the output shown.
2. Implement a new class with base class Number that is called Digital. It is to store
the number 0 and 1. Display the int, long, float, double values as shown above.
A good implementation will have a constructor that throws a
NumberFormatException exception if other than a 0 or 1 is given as argument. Test
it by calling all the member functions.
Read the Java API documentation for the Closeable and Flushable interfaces. The links to
the online version of the documentation are:
https://docs.oracle.com/javase/8/docs/api/
Go to the java.io package and click on the interface links. Observe the number and names of
classes that implement these interfaces.

We will now look at choosing between interfaces and abstract classes.
Abstract class or interface?
As we have already observed, an interface is a “extreme” version of an abstract class with all abstract
methods. This means wat it is possible to write an interface as an abstract class. So how to you choose
between them?
We have already pointed out the differences between abstract classes and interfaces. We noted that
interfaces have several restrictions compared to abstract classes:
1. Abstract classes can have all the attributes that a normal class can have, but interfaces can only
have constants.
2. An abstract class can have protected constructors but an interface cannot define constructors.
3. An abstract class can have concrete or default methods implemented but interfaces can only have
public abstract methods.
On the other hand, due to these restrictions an interface has the following advantage:
A class can implement any number of interfaces (multiple inheritance)
This is important because interfaces allow specification of multiple features in a single class. However,
an abstract class can only be the unique base class of another class. In other words, the ideas
incorporated in the development two abstract classes cannot be applied to a single derived class because
of the limits on inheritance.
This point was demonstrated with the Closeable and Flushable interfaces from the java.io
package discussed in the previous section. Since they are interfaces, both can be implemented by the
various java.io classes that implement I/O streams. However, if they were abstract classes then the
same java.io classes could only extend one of these.
The multiple inheritance of interfaces can make them more desirable that abstract classes. This is
because, at the time of development, other interfaces may exist that could be used in future classes.
Even the chance that such an interface may be required can tip the odds in favour of creating an interface
instead of an abstract class.
On the other hand, an abstract class allows creation of concreate methods that may be used as default
methods for derived class. We can also implement constructors and attributes in abstract classes that
may be important for the concept we are trying to introduce. By having these in the abstract class the
users do not have to re-implement the code in each class that extends it.
CSC72002 Study Guide Abstract classes and interfaces
2-12

 Activity 2-2: Java API abstract classes and interfaces
Read the textbook Section 13.8 and 13-9 (pp. 539-547). The second section is an example
coding of a class to represent rational numbers. If you are not familiar with rational numbers
this may not be clear so just read the relevant abstract class information. You do not have to
know about rational numbers!
Implement the examples in Section 13.8 of the reading as you read about first the abstract class
Animal then the interface Edible. Think about why the second is less restrictive.

That’s enough for this short topic.
Summary
In this Topic we have looked at abstract classes and interfaces and some of the examples from the Java
API packages. We first saw how abstract classes are classes that cannot be instantiated but are important
for providing re-usable code that other programmers may use. We also saw the ultimate abstract classes
which are called interfaces in Java. An interface has all abstract methods which provides the additional
attribute that a class can implement multiple interfaces. We also saw how abstract classes and interfaces
are used in the Java API for us to use by examining some examples of each.

CLICK HERE TO GET A PROFESSIONAL WRITER TO WORK ON THIS PAPER AND OTHER SIMILAR PAPERS

CLICK THE BUTTON TO MAKE YOUR ORDER

YOU MAY ALSO READ ...  Is the policy based on knowledge that has been tested to some degree?