Lecture - Java Classes 4: Inheritance, Abstract Classes, and Interfaces

Java provides support for many of the key OO concepts through its class structure:

- Inheritance

- Polymorphism

- Classification

This lecture considers such support through the mechanism of:

- Inheritance (extends)

- Abstract classes

- Interfaces

- Method overloading & overriding

- Dynamic Binding

 

 

 

Reference:            Lewis & Loftus Ch. 5 (5.4),

                               Ch. 7 (7.2-7.8)

                               Kamin, Ch. 12, 5, 8

Motivation

Java provides explicit support for many of the fundamental concepts of Object Orientation:

Classification:  classes, interfaces, packages

Encapsulation:  classes, visibility modifiers

Inheritance:  class inheritance (extends), abstract classes

Polymorphism:  method overloading, dynamic binding, interfaces

This support is fundamental in providing the power of Java:

- Code reuse

+ classification, encapsulation

- Complexity management

+ encapsulation, inheritance, classification

- Easy extensibility

+ inheritance

- "Dynamic" behaviours

+ polymorphism

Inheritance: Principles

Inheritance allows the creation of new classes as extensions of an existing class:

- Existing class is unchanged

- Extending class inherits all code from the superclass

+ its attributes and methods

- Extending class can define its own, additional attributes and methods

- Extending code can over-ride the behaviour of the super-class

+ over-ride methods

Inheritance allows

- customisation of an existing class to fit a new application

- extraction and grouping of common properties under a single class

- simple creation of specialised sub-classes of a more general super-class

Inheritance in the API

Inheritance is not limited solely to user-code

- It is used extensively in the core API

+ Structures, Organises, Extends capabilities

For Instance:

- AWT Components

- extend Component class

- Container class,

- etc.

- IO Package

- InputStreams, OutputStreams, Readers, & Writers all super-classes

- lang Package

- numeric wrapper classes (e.g., Double) all extend the same super-class

- Indeed, all classes eventually trace back their roots to java.lang's Object class

AWT Component Hierarchy of Inheritance

Extending a Class

At the heart of Java's inheritance mechanism is the extends statement:

- a subclass (child) extends the superclass (parent)

Syntax:

 

[modifier] class A extends B [...] {

For instance:

 

public class MyApplet extends Applet

         implements ActionListener {

 

public class Student extends Person { ...}

public class Teacher extends Person { ...}

A subclass inherits all the methods and attributes of its superclass(es)

- visibility modifiers affect this: private methods & attributes can not be accessed in a sub-class. Use protected to allow subclass access

- For instance in a user Applet:

- getImage() method to load image files is inherited from Applet class

- add() method to add Components to screen is inherited from Container class

- getSize() method to determine screen size is inherited from Component class

Super & Constructor Hierarchies

Sub-classes may explicitly reference their superclass

- using the reserved word super

+ corollary to this

Enables the subclass to:

- access the superclass constructors

- access over-ridden methods of the superclass

Note that super is redundant (not required) for attributes or methods that haven't been over-ridden

Constructor access is particularly important:

- construction of a subclass automatically entails construction of all super-classes

The rules for superclass constructor access are:

- A subclass constructor can call the superclass constructor as super(param1,param2,...)

- The superclass constructor call must be the first statement in the sub-class' constructor

- A subclass constructor without a super call as the first statement has an implicit super() inserted as the first statement

- i.e., Java will "forcibly" construct the superclass using the empty constructor

Parent Example

/********************************************************

* ParentEx: A simple superclass with a single attribute

* (int), constructor, and 2 methods. Used to illustrate

* Java's inheritance mechanism. See the ChildEx class for

* a subclass that extends this class and uses its methods.

* @author Spike Barlow

* @date 3/9/1999

********************************************************/

public class ParentEx {

 

  protected int  x; // Only class & subclasses can see

 

/******************************

* Single, obvious constructor.

******************************/

ParentEx(int n) {

 

  x = n;

}

 

/******************************************************

* Single method. Reset the attribute's value to that

* supplied.

*********************************************************/

public void reset(int newValue) {

 

  x = newValue;

}

 

/**************************************************

* Convert the object to a String representation.

**************************************************/

public String toString() {

 

  return "x: " + x;

}

}

Child Example

/********************************************************

* ChildEx: A simple subclass that extends ParentEx.

* ChildEx adds an attribute, two methods, overloads an

* exisiting method of ParentEx and over-rides another.

* Finally, there is a simple main method that illustrates

* the class (and hence inheritance) "in action"

* @author Spike Barlow

* @date 3/9/1999

********************************************************/

public class ChildEx extends ParentEx {

 

  protected double y; // Only visible in class & subs

 

/*********************************************************

* Single constructor. Note the invokation of the super

* class' constructor as the first statement of the

* constructor. If that was not done a super() call would

* have been implicitly inserted by the Java compiler.

********************************************************/

ChildEx(int initialX, double initialY) {

 

  super(initialX);

  y = initialY;

}

 

/********************************************************

* Reset the attributes. Overloads the reset of the super

* class and employs it for implementation.

********************************************************/

public void reset(int newX, double newY) {

 

  reset(newX);        // Could also have used

                      // super.reset(newX);

  y = newY;

}

Child Output

/*****************************

* Square both the attributes.

*****************************/

public void square() {

 

  x *= x;

  y *= y;

}

 

/********************************************************

* Convert the class into a suitable String presentation.

* Defining such a method allows the class to be given

* directly to print/println methods for output.

********************************************************/

public String toString() {

 

  return "x: " + x + ", y: " + y;

}

 

/********************************************************

* A main method that exercises the class by constructing

* an instance and using the various methods of the class

* and its parent.

********************************************************/

public static void main(String[] args) {

 

  ChildEx child = new ChildEx(10,Math.PI);

  System.out.println(child);

  child.reset(-3,Math.E);

  System.out.println(child);

  child.square();

  System.out.println(child);

  child.reset(0);

  System.out.println(child);

}

}

         OUTPUT

x: 10, y: 3.141592653589793

x: -3, y: 2.718281828459045

x: 9, y: 7.3890560989306495

x: 0, y: 7.3890560989306495

 

Abstract Classes

Java provides a mechanism for defining "prescriptive" superclasses:

- class cannot be instantiated, only its subclasses

- class may define methods and attributes which all subclasses inherit

- class may define abstract methods: methods which the subclasses must realise to be concrete (can be instantiated)

+ only the method's signature is defined

+ if a subclass does not realise all of the superclass' abstract methods then it too is automatically an abstract class

The classes are known as abstract classes

The core API makes heavy use of abstract classes:

- AWT's Component class is abstract

- IO's InputStream, OutputStream, Reader & Writer are abstract classes

- TEXT's Format class (subclasses of DateFormat etc.) is an abstract class

Syntax of Abstract Classes & Methods

A class which is abstract must state so in its definition

- Abstract due to having at least one abstract method or simply the author intends it to be abstract.

 

[modifier] abstract class <ClassName> {

 

   e.g.,

 

   public abstract class Person {

Abstract methods also employ the abstract keyword in their definition

- Only the method's signature is defined

 

[modifiers] abstract <type> method([args]);

 

   e.g.

   public abstract int getNumber();

   protected abstract Species[]

             getNeighbours(Position pos);

Subclasses of an abstract class use the standard extends syntax:

 

   e.g.,

   public class Student extends Person {

Dynamic Binding

Java employs a technique known as dynamic binding in order to determine which method to run

- Determination is made at run-time for public and package visibility methods

- Stems from methods being over-ridden

+ Compiler can't determine which particular class the object was constructed from, hence which method to use

+ Hence only JVM (interpreter) can determine true object class and invoke the appropriate method

Java uses the actual type (actual class it was constructed from) in determining an appropriate method to call as opposed to the declared type (the type that the identifier/attribute was declared as)

Extremely powerful: Java "automatically" invokes the appropriate method based on the object

Slows execution: interpreter needs to check each object's type before determining what method to call

Dynamic Binding Example

/********************************************************

* DynamicExample: A class to show dynamic binding at work.

* A superclass and subclass exist as an earlier example

* called ParentEx and ChildEx (respectively). Instances

* of each are created and their toString() method employed

* implicitly by System.out.println.

* A 3rd instance is created, it is declared as ParentEx,

* the superclass, but instantiated (constructed) using

* the subclass.

* The [implicit] toString() call illustrates dynamic

* method binding: the toString() associated with the

* actual object which, of type ChildEx is employed rather

* than that of the declared reference type.

* @author Spike Barlow

* @date 3/9/1999

********************************************************/

public class DynamicExample {

 

/******************************************************

* Create 3 different instances in order to check which

* toString() method is employed in each case.

******************************************************/

public static void main(String[] args) {

 

  ParentEx parent = new ParentEx(50);

  System.out.println(parent);

  ChildEx child = new ChildEx(7,1.0);

  System.out.println(child);

 

  ParentEx which = new ChildEx(18,0.0);

  System.out.println(which);

}

}

 

         OUTPUT

x: 50

x: 7, y: 1.0

x: 18, y: 0.0

 

Interfaces

Interfaces are Java's mechanism for supporting polymorphism

- Different (often fundamentally) objects with a common set of behaviours (methods)

Interfaces are prescriptive:

- Define a set of methods which a class must implement if the class is said to implement the interface

A single class may implement multiple interfaces

- has behaviour that matches each of the interfaces

Interfaces are used heavily in the AWT's event model

- each event has a corresponding interface

+ e.g., ActionEvent has a corresponding interface known as ActionListener

- each interface specifies the corresponding methods that must be implemented

+ e.g., ActionListener interface specifies a method with the signature:

 

         public void actionPerformed(ActionEvent e);

Interface Syntax

A class which is an interface must state so in its definition

 

[modifier] interface <InterfaceName> {

 

   e.g.,

 

   public interface Vehicle {

Interfaces may only contain method signatures and static final attributes (constants)

- No need for the abstract keyword

 

[modifiers] <type> method([args]);

 

   e.g.

   public typeOfMotion getMotionType();

   public People[] getPassengers();

Classes which implement an interface specify so in their definition

 

   e.g.,

   public class Submarine implements

        Vehicle, Submersible {

 

Abstract Classes vs. Interfaces

Java allows only single-class inheritance

- A class can only extend a single class (no multiple-inheritance)

- A design decision, other OO languages such as C++ allow multiple-inheritance

+ Still debated as to whether right choice (simplicity vs. ability to precisely specify)

Abstract classes and interfaces both are prescriptive. However:

- Abstract classes define a hierarchical relationship: Class B is a special-type of class A.

- Interfaces define a form of behaviour: Class B has behaviour as specified by Interface B

Interfaces can be used to "mimic" the result of multiple inheritance

- Class extends main parent class and implements interfaces that describe the behaviour of the other classes

- For instance

 

public class APC extends Vehicle implements

WeaponPlatform, PassengerVehicle {

Method Overloading & Overriding

Method overloading and overriding provide precise control in specifying the behaviour of a class

Method Overloading

- Multiple methods with the same name but different parameters

+ different numbers, type and/or order

- Appropriate method is invoked based on the parameters passed.

Method Overriding

- New definition is given for a method in a subclass of the one it was originally defined in.

+ same parameter numbers, type and order

- Appropriate method will be called based on dynamic binding principle (determine actual class of object reference)

The Parent/Child example illustrates both of these

- ChildEx overloads (extends functionality) the reset() method it inherits from ParentEx and overrides (defines new behaviour)  the toString() method it inherited from ParentEx.

Review

Inheritance

- Principles

- Syntax

- In the API

- super

- Dynamic Binding

Abstract Classes

Interfaces

Abstract classes vs. Interfaces

Method Overloading & Overriding

The University of Southern California does not screen or control the content on this website and thus does not guarantee the accuracy, integrity, or quality of such content. All content on this website is provided by and is the sole responsibility of the person from which such content originated, and such content does not necessarily reflect the opinions of the University administration or the Board of Trustees