Inheritance

Ch. 9: Object-Oriented Programming: Classes/Inheritance Including super/this clause/ abstract classes and interfaces implementation November 2009 Cr...
Author: Phoebe Collins
3 downloads 0 Views 853KB Size
Ch. 9: Object-Oriented Programming: Classes/Inheritance Including super/this clause/ abstract classes and interfaces implementation November 2009

Creating Packages 

We can import packages into programs    

Group of related classes and interfaces Help manage complexity of application components Facilitate software reuse Provide convention for unique class names 

Popular package-naming convention 

Reverse Internet domain name  e.g., com.deitel

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

// package example… // Time1 class declaration maintains the time in 24-hour format. package com.deitel.jhtp5.ch08; import java.text.DecimalFormat; public class Time1 { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59

Class Time1 is in directory com/deitel/jhtp5/ch08 Class Time1 is placed in this package

import classtoDecimalFormat from package // Time1 constructor initializes each instance variable zero; java.text // ensures that each Time1 object starts in a consistent state public Time1() { setTime( 0, 0, 0 ); } // set a new time value using universal time; perform // validity checks on the data; set invalid values to zero public void setTime( int h, int m, int s )

Package Access 

Package access 

Variable or method does not have member access modifier

Software Reusability 

Java  

Framework for achieving software reusability Rapid applications development (RAD) 

e.g., creating a GUI application quickly

Ch. 9: Object-Oriented Programming: Classes/Inheritance

Ch. 9: Object-Oriented Programming: Classes/Inheritance 

Class hierarchy 

Direct superclass 



Indirect superclass 



Inherited two or more levels up hierarchy

Single inheritance 



Inherited explicitly (one level up hierarchy)

Inherits from one superclass

Multiple inheritance 

Inherits from multiple superclasses 

Java does not support multiple inheritance

Introduction 

Abstraction 



Focus on commonalities among objects in system

“is-a” vs. “has-a” 

“is-a”   

Inheritance subclass object treated as superclass object Example: Car is a vehicle 



Vehicle properties/behaviors also car properties/behaviors

“has-a”   

Composition Object contains one or more objects of other classes as members Example: Car has a steering wheel

Inheritance (cont’d) subclass or

superclass extends

derived class

or base class

subinterface

extends

superinterface

class

implements

interface

extend clause 

We say that one class can extend another by absorbing its state and behavior.  

superclass: The parent class that is being extended. subclass: The child class that extends the superclass and inherits its behavior. 

The subclass receives a copy of every field and method from its superclass.

class B extends A class B extends A { . . // additions to, and modifications of, // stuff inherited from class A . }

Example..

Another example: public class Lawyer extends Employee { public Lawyer(int years) { super(years); //call Employee constructor } ... }

Example… class Vehicle { int registrationNumber; Person owner; // (assuming that a Person class has been defined) void transferOwnership(Person newOwner) { ... } ... } class Car extends Vehicle { int numberOfDoors; ... } class Truck extends Vehicle { int numberOfAxels; ... } class Motorcycle extends Vehicle { boolean hasSidecar; ... }

Method Access Control-revisited    

Public – everyone has access Private – no one outside this class has access Protected – subclasses have access Default – package-access

Method Overloading 

Method overloading  

Several methods of the same name Different parameter set for each method  

Number of parameters Parameter types

Another example…with draw(…,…,…) public class DataArtist { ... public void draw(String s) { ... } public void draw(int i) { ... } public void draw(double f) { ... } public void draw(int i, double f) { ... } }

The same name but different # of arguments

Superclasses and Subclasses 

Superclasses and subclasses 

Object of one class “is an” object of another class 

Example: Rectangle is quadrilateral.   



Class Rectangle inherits from class Quadrilateral Quadrilateral: superclass Rectangle: subclass

Superclass typically represents larger set of objects than subclasses 

Example: 



superclass: Vehicle  Cars, trucks, boats, bicycles, … subclass: Car  Smaller, more-specific subset of vehicles

Superclasses and Subclasses (Cont.) 

Inheritance hierarchy  

Inheritance relationships: tree-like hierarchy structure Each class becomes 

superclass 

Supply data/behaviors to other classes

OR 

subclass 

Inherit data/behaviors from other classes

Extends…and some more issues.. public class Bicycle { // the Bicycle class has three fields public int cadence; public int gear; public int speed; // the Bicycle class has one constructor public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; }

// the Bicycle class has four methods public void setCadence(int newValue) { cadence = newValue; } public void setGear(int newValue) { gear = newValue; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } }

a Bicycle class

A class declaration for a MountainBike class that is a subclass of Bicycle might look like this: public class MountainBike extends Bicycle { // the MountainBike subclass has one field public int seatHeight; // the MountainBike subclass has one constructor public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) { super(startCadence, startSpeed, startGear); seatHeight = startHeight; } // the MountainBike subclass has one method public void setHeight(int newValue) { seatHeight = newValue; } }

Another example with extends

Example with extends public class SuperClass2 { // No-arg constructor public SuperClass2() { System.out.println("This is the superclass " + "no-arg constructor."); } // Constructor #2 public SuperClass2(int arg) { System.out.println("The following argument was " + "passed to the superclass " + "constructor: " + arg); } }

Example with extends public class SubClass2 extends SuperClass2 { // Constructor public SubClass2() { // Call the superclass constructor. super(10); // Display a message. System.out.println("This is the subclass " + "constructor."); } }

Inheritance (cont’d… extend) 

In Java, a subclass can extend only one superclass.



In Java, a subinterface can extend one superinterface



In Java, a class can implement several interfaces — this is Java’s form of multiple inheritance.

Inheritance (cont’d) 

Inheritance plays a dual role: 

A subclass reuses the code from the superclass.



A subclass (or a class that implements an interface) inherits the data type of the superclass (or the interface) as its own secondary type.

Inheritance (cont’d) 

Inheritance leads to a hierarchy of classes and/or interfaces in an application: Game Solitaire

GameFor2 BoardGame Chess

Backgammon

Inheritance (cont’d) Shape

TwoDimensionalShape

Circle

Square

Triangle

ThreeDimensionalShape

Sphere

Cube

Tetrahedron

Inheritance hierarchy for Shapes.

YOU SHOULD CREATE A DIAGRAM FOR YOUR PROGRAMS

Let’s have a look at the

protected Members 

protected access  

Intermediate level of protection between public and private protected members accessible to   



superclass members subclass members Class members in the same package

Subclass access the superclass member 

Keyword super and a dot (.)

Encapsulation 

encapsulation: Hiding the implementation details of an object from the clients of the object. 



(Protecting the object's fields from modification by clients.)

Encapsulating objects provides abstraction; we can use them without knowing how they work. The object has:  

an external view (its behavior) an internal view (the state that accomplishes the behavior)

Encapsulation/privacy 

Encapsulation means that all data members (fields) of a class are declared private. Some methods may be private, too.



The class interacts with other classes (called the clients of this class) only through the class’s constructors and public methods.



Constructors and public methods of a class serve as the interface to class’s clients.

Encapsulation (cont’d) 

Ensures that structural changes remain local: 

Usually, the structure of a class (as defined by its fields) changes more often than the class’ constructors and methods.



Encapsulation ensures that when fields change, no changes are needed in other classes (a principle known as “locality” in reference).

Classes Access Control    

Public – everyone has access Private – no one outside this class has access Protected – subclasses have access Default – package-access

Review the keyword static 



The keyword static does not mean "unmoving" as it does in common English usage. Instead is means something like "class" or "unique". Ordinary members have one copy per instance, whereas a static member has only one copy, which is shared by all instances. Ordinary (non-static) fields are sometimes called "instance variables".

Variable Keywords The following keywords are a special type of reference variable: ■ super Reference variable referring to the immediate superclass. ■ this Reference variable referring to the current instance of an object. subclass

this

or

derived class

super

superclass

extends

or

this

base class

Learning About the this Reference 

Instantiate object from class  



Memory reserved for each instance field in class Not necessary to store separate copy of each variable and method for each instantiation of class

In Java  

One copy of each method in class stored All instantiated objects can use one copy

Learning About the this Reference (continued) 

Reference  

Object’s memory address Implicit 

Automatically understood without actually being written

Learning About the this Reference (continued) 

this reference    

Reference to object Passed to any object’s nonstatic class method Reserved word in Java Don’t need to use this reference in methods you write

super(parameter-list); 

Here (above), parameter-list specifies any parameters needed by the constructor(s) in the superclass. super( ) must always be the first statement executed inside a subclass’ constructor.

Example

// This program uses inheritance to extend Box. class Box { double width; double height; double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } }

Using super() class BoxWeight extends Box { double weight; // weight of box // initialize width, height, and depth using super() BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass’s constructor weight = m; } }

A Second Use : super // Using super to overcome name hiding. class A { int i; }

What will be the output?

// Create a subclass by extending class A. class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i = a; // i in A i = b; // i in B } void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } }

This program displays the following: i in superclass: 1 i in subclass: 2

Relationship between Superclasses and Subclasses 

Superclass and subclass relationship 

Example: Point/circle inheritance hierarchy 

Point 



x-y coordinate pair

Circle  

x-y coordinate pair Radius

Inheritance in classes / subclasses

subclass or derived class

superclass extends

or base class

Extends again Inheritance in subclasses

Let’s see an example..

1 2 3

// Point.java // Point class declaration represents an x-y coordinate pair. Maintain x-

4

public class Point {

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

and ycoordinates as private instance variables.

private int x; // x part of coordinate pair private int y; // y part of coordinate pair

Implicit call to constructor

// no-argument constructor Object public Point() { // implicit call to Object constructor occurs here } // constructor public Point( int xValue, int yValue ) { // implicit call to Object constructor occurs here x = xValue; // no need for validation y = yValue; // no need for validation } // set x in coordinate pair public void setX( int xValue ) { x = xValue; // no need for validation }

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

// return x from coordinate pair public int getX() { return x; }

Point.java Lines 47-50 Override method toString of class Object.

// set y in coordinate pair public void setY( int yValue ) { y = yValue; // no need for validation } // return y from coordinate pair public int getY() { return y; }

Override method toString of class Object

// return String representation of Point object public String toString() { return "[" + x + ", " + y + "]"; } } // end class Point

Inheritance programming 

IS actually when:    

creating subclasses overriding behavior multiple levels of inheritance interacting with the superclass using the super keyword

Override an inherited method

Overriding 





Indicates that a method declaration is intended to override a method declaration in a superclass. The method is re re--implemented in the derived class Method Overriding is achieved when a subclass non--static methods defined in the overrides non superclass, following which the new method implementation in the subclass that is executed.

1 2 3 4

// PointTest.java // Testing class Point. import javax.swing.JOptionPane;

5

public class PointTest {

6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

Instantiate Point object

public static void main( String[] args ) { Point point = new Point( 72, 115 ); // create Point object // get point coordinates String output = "X coordinate is " + point.getX() +Change the value of and y- coordinates "\nY coordinate is " + point.getY(); point.setX( 10 ); // set x-coordinate point.setY( 20 ); // set y-coordinate // get String representation of new point value output += "\n\nThe new location of point is " + point; JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); } // end main } // end class PointTest

point’s xImplicitly call point’s toString method

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

// Circle.java // Circle class contains x-y coordinate pair and radius.

Maintain x-y coordinates public class Circle { radius as private private int x; // x-coordinate of Circle's center private int y; // y-coordinate of Circle's center instance variables. private double radius; // Circle's radius

and

// no-argument constructor public Circle() { // implicit call to Object constructor occurs here } // constructor public Circle( int xValue, int yValue, double radiusValue ) { // implicit call to Object constructor occurs here x = xValue; // no need for validation y = yValue; // no need for validation setRadius( radiusValue ); } // set x in coordinate pair public void setX( int xValue ) { x = xValue; // no need for validation }

Note code similar to Point code.

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

// return x from coordinate pair public int getX() { return x; } // set y in coordinate pair public void setY( int yValue ) { y = yValue; // no need for validation }

Note code similar to Point code.

// return y from coordinate pair public int getY() { return y; } // set radius public void setRadius( double radiusValue ) { radius = ( radiusValue < 0.0 ? 0.0 : radiusValue ); } // return radius public double getRadius() { return radius; }

Ensure non-negative value for radius.

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

// calculate and return diameter public double getDiameter() { return 2 * radius; } // calculate and return circumference public double getCircumference() { return Math.PI * getDiameter(); }

Circle.java

// calculate and return area public double getArea() { return Math.PI * radius * radius; } // return String representation of Circle object public String toString() { return "Center = [" + x + ", " + y + "]; Radius = " + radius; } } // end class Circle

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

// CircleTest.java // Testing class Circle. import java.text.DecimalFormat; import javax.swing.JOptionPane; public class CircleTest {

Create Circle object.

public static void main( String[] args ) { Circle circle = new Circle( 37, 43, 2.5 ); // create Circle object // get Circle's initial x-y coordinates and radius String output = "X coordinate is " + circle.getX() + "\nY coordinate is " + circle.getY() + "\nRadius is " + circle.getRadius();

Explicitly call circle’s toString method

circle.setX( 35 ); // set new x-coordinate circle.setY( 20 ); // set new y-coordinate circle.setRadius( 4.25 ); // set new radius // get String representation of new circle value Use set methods to instance output += "\n\nThe new location and radius of circle are\n"variable. + circle.toString(); // format floating-point values with 2 digits of precision DecimalFormat twoDigits = new DecimalFormat( "0.00" );

modify private

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

// get Circle's diameter output += "\nDiameter is " + twoDigits.format( circle.getDiameter() ); // get Circle's circumference output += "\nCircumference is " + twoDigits.format( circle.getCircumference() ); // get Circle's area output += "\nArea is " + twoDigits.format( circle.getArea() ); JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); } // end main } // end class CircleTest

Use get methods to obtain circle’s diameter, circumference and area.

public class Circle2 extends Point Some properties hands-on…

1 2 3

// Fig. 9.8: Circle2.java // Circle2 class inherits from Point.

4

public class

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

Circle2 extends Point {

Class Circle2 extends class Point.

private double radius; // Circle2's radius // no-argument constructor public Circle2() { // implicit call to Point constructor occurs here } // constructor public Circle2( int xValue, int yValue, double radiusValue ) { // implicit call to Point constructor occurs here x = xValue; // not allowed: x private in Point y = yValue; // not allowed: y private in Point setRadius( radiusValue ); } // set radius public void setRadius( double radiusValue ) { radius = ( radiusValue < 0.0 ? 0.0 : radiusValue ); }

Maintain private instance variable radius.

Attempting to access superclass Point’s private instance variables x and y results in syntax errors.

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

// calculate and return diameter public double getDiameter() { return 2 * radius; } // calculate and return circumference public double getCircumference() { return Math.PI * getDiameter(); } // calculate and return area public double getArea() { return Math.PI * radius * radius; } // return String representation of Circle object public String toString() { // use of x and y not allowed: x and y private in Point return "Center = [" + x + ", " + y + "]; Radius = " + radius; } } // end class Circle2

Attempting to access superclass Point’s private instance variables x and y results in syntax errors.

Circle2.java:17: x has private access in Point x = xValue; // not allowed: x private in Point ^ Circle2.java:18: y has private access in Point y = yValue; // not allowed: y private in Point ^ Circle2.java:56: x has private access in Point return "Center = [" + x + ", " + y + "]; Radius = " + radius; ^ Circle2.java:56: y has private access in Point return "Center = [" + x + ", " + y + "]; Radius = " + radius; ^ 4 errors

Attempting to access superclass Point’s private instance variables x and y results in syntax errors.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

// Point2.java // Point2 class declaration represents an x-y coordinate pair. public class Point2 { protected int x; // x part of coordinate pair protected int y; // y part of coordinate pair // no-argument constructor public Point2() { // implicit call to Object constructor occurs here } // constructor public Point2( int xValue, int yValue ) { // implicit call to Object constructor occurs here x = xValue; // no need for validation y = yValue; // no need for validation } // set x in coordinate pair public void setX( int xValue ) { x = xValue; // no need for validation }

Maintain x- and y-coordinates as protected instance variables, accessible to subclasses.

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

// return x from coordinate pair public int getX() { return x; } // set y in coordinate pair public void setY( int yValue ) { y = yValue; // no need for validation } // return y from coordinate pair public int getY() { return y; } // return String representation of Point2 object public String toString() { return "[" + x + ", " + y + "]"; } } // end class Point2

1 2 3 4

// Circle3.java // Circle3 class inherits from Point2 and has access to Point2Class Circle3 inherits from // protected members x and y. class Point2. Maintain private instance

5

public class Circle3 extends Point2 {

6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

variables radius. private double radius; // Circle3's radius // no-argument constructor public Circle3() { // implicit call to Point2 constructor occurs here }

Implicitly calls superclasse’s default constructor.

// constructor inherited instance public Circle3( int xValue, int yValue, doubleModify radiusValue ) variables x and y, declared { // implicit call to Point2 constructor occurs protected here in superclass x = xValue; // no need for validation Point2. y = yValue; // no need for validation setRadius( radiusValue ); } // set radius public void setRadius( double radiusValue ) { radius = ( radiusValue < 0.0 ? 0.0 : radiusValue ); }

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

// return radius public double getRadius() { return radius; } // calculate and return diameter public double getDiameter() { return 2 * radius; } // calculate and return circumference public double getCircumference() { return Math.PI * getDiameter(); } // calculate and return area public double getArea() { return Math.PI * radius * radius; } // return String representation of Circle3 object public String toString() { return "Center = [" + x + ", " + y + "]; Radius = " + radius; } } // end class Circle3

Access inherited instance variables x and y, declared protected in superclass Point2.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// CircleTest3.java // Testing class Circle3. import java.text.DecimalFormat; import javax.swing.JOptionPane; public class CircleTest3 { public static void main( String[] args ) { // instantiate Circle object Circle3 circle = new Circle3( 37, 43, 2.5 ); // get Circle3's initial x-y coordinates and radius String output = "X coordinate is " + circle.getX() + "\nY coordinate is " + circle.getY() + "\nRadius is " + circle.getRadius(); circle.setX( 35 ); // set new x-coordinate circle.setY( 20 ); // set new y-coordinate circle.setRadius( 4.25 ); // set new radius

Create Circle3 object. Use Circle3 get method to access private instance variables. Use inherited get methods to access inherited protected instance variables x and y.

Use inherited set methods to modify inherited // get String representation of new circle value protected datatox and y. Use Circle3 set method output += "\n\nThe new location and radius of circle are\n" + modify private data circle.toString(); radius.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

// format floating-point values with 2 digits of precision DecimalFormat twoDigits = new DecimalFormat( "0.00" ); // get Circle's diameter output += "\nDiameter is " + twoDigits.format( circle.getDiameter() ); // get Circle's circumference output += "\nCircumference is " + twoDigits.format( circle.getCircumference() ); // get Circle's area output += "\nArea is " + twoDigits.format( circle.getArea() ); JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); } // end method main } // end class CircleTest3

Object base class 

All Java objects derive from the Object base class. These is true even though you don't explicitly include the "extend Object" in your class definition.



For example,



public class Test { ... } is equivalent to public class Test extends Object { ... }

java.lang 

Class Object 

java.lang.Object

All Java objects derive from the Object base class. Visit the onon-line JavaDoc at: http://java.sun.com/j2se/1.4.2/docs/api/index.html

Three-Level Inheritance Hierarchy 

Three level point/circle/cylinder hierarchy 

Point 



Circle  



x-y coordinate pair x-y coordinate pair Radius

Cylinder   

x-y coordinate pair Radius Height

In this way YOU Should think the OOP paradigm. General Programming Considerations ■ Avoid designing a class that has no methods. ■ Use design patterns. ■ Use overloading rather than logic. ■ Avoid long argument lists.

1 // Fig. 9.15: Cylinder.java Maintain private instance 2 // Cylinder class inherits from Circle4. variable height. 3 4 public class Cylinder extends Circle4 { 5 private double height; // Cylinder's height 6 Class Cylinder 7 // no-argument constructor class Circle4. 8 public Cylinder() 9 { 10 // implicit call to Circle4 constructor occurs here 11 } 12 13 // constructor 14 public Cylinder( int xValue, int yValue, double radiusValue, 15 double heightValue ) 16 { 17 super( xValue, yValue, radiusValue ); // call Circle4 constructor 18 setHeight( heightValue ); 19 } 20 21 // set Cylinder's height 22 public void setHeight( double heightValue ) 23 { 24 height = ( heightValue < 0.0 ? 0.0 : heightValue ); 25 } 26

extends

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

// get Cylinder's height public double getHeight() { return height; }

Redefine superclass Circle4’s method Invoke superclass // override Circle4 method getArea to calculate Cylinder area getArea to return Circle4’s getArea public double getArea() Cylinder surface area. method using keyword super. { return 2 * super.getArea() + getCircumference() * getHeight(); } // calculate Cylinder volume public double getVolume() { return super.getArea() * getHeight(); } // return String representation of Cylinder object public String toString() { return super.toString() + "; Height = " + getHeight(); } } // end class Cylinder

Redefine class Circle4’s method toString. Invoke superclass Circle4’s toString method using keyword super.

polymorphism 

polymorphism:

The ability for the same code to be used with several different types of objects and behave differently depending on the type of object used.

Abstract Classes

Abstract Classes 

An Abstract class is a conceptual class. 



An Abstract class cannot be instantiated – objects cannot be recreated. Only extended!

Abstract classes provide a common root for a group of classes.

Abstract Classes 



It is useful to declare classes for which the programmer never intends to instantiate objects. objects Such classes are called abstract classes. Because they are used only as superclasses in inheritance hierarchies, we refer to them as abstract superclasses.

Abstract Classes 



These classes cannot be used to instantiate objects, because, as we will soon see, abstract classes are incomplete. Subclasses must declare the "missing missing pieces." pieces

Abstract Class Syntax abstract class ClassName { ... … abstract Type MethodName1(); … … Type Method2() { // method body }

}  

When a class contains one or more abstract methods, it should be declared as abstract class. We cannot declare abstract constructors or abstract static methods.

Ex. using an abstract class abstract class Cat { //abstract classes can have variables String abstractClassName = "Cat"; //abstract classes can have methods String getAbstractClassName() { return abstractClassName; } //this must be implemented in any class extending Cat

abstract String getClassName(); } //you can not extend from two classes at once class Himalayan extends Cat{ Cat String className = "Himalayan"; public Himalayan() {} //must have this method, // because Cat declared it as an abstract String getClassName() { return className; }

Ex. using an abstract class (cont’ed) public static void main(String[] args) { //you can not instantiate an abstract class //Cat percy = new Cat(); //does not work Himalayan cappuccino = new Himalayan(); System.out.println(cappuccino.getAbstractClassName()); //output is: Cat System.out.println(cappuccino.getClassName()); //output is: Himalayan } }

Abstract Classes Properties 

A class with one or more abstract methods is automatically abstract and it cannot be instantiated.



A class declared abstract, even with no abstract methods can not be instantiated.



A subclass of an abstract class can be instantiated if it overrides all abstract methods. methods

Another example abstract class Animal extends Object { int age; Animal() { super();} int getAge() {...} } public final class Dog extends Animal { final int legs = 4; final static boolean hasTail = yes; Dog() { this(“Laika”); } Dog(String s) { super(); … } int getAge(String name) {…} }

Abstract Classes and Methods 

Abstract classes   

Are superclasses (called abstract superclasses) Cannot be instantiated Incomplete 



subclasses fill in "missing pieces"

Concrete classes   

Can be instantiated Implement every method they declare Provide specifics

Abstract Classes and Methods (Cont.) 



Abstract classes not required, but reduce client code dependencies To make a class abstract  

Declare with keyword abstract Contain one or more abstract methods public abstract void draw();



Abstract methods 

No implementation, must be overridden

Abstract Classes and Methods (Cont.) 

Application example 

Abstract class Shape 



Circle, Triangle, Rectangle extends Shape 



Declares draw as abstract method

Each must implement draw

Each object can draw itself

Case Study: Inheriting Interface and Implementation 

Make abstract superclass Shape 

Abstract method (must be implemented)  



getName, print Default implementation does not make sense

Methods may be overridden 

getArea, getVolume 





Default implementations return 0.0

If not overridden, uses superclass default implementation

Subclasses Point, Circle, Cylinder

Inheriting Interface and Implementation Shape

Point

Circle

Cylinder

Shape hierarchy class diagram.

Inheriting Interface and Implementation getArea

getVolume

getName

print

Shape

0.0

0.0

= 0

= 0

Point

0.0

0.0

"Point"

[x,y]

Circle

pr2

0.0

"Circle"

center=[x,y]; radius=r

2pr2 +2prh

pr2h

"Cylinder"

center=[x,y]; radius=r; height=h

Cylinder

Polimorphic interface for the Shape hierarchy classes.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

Outline

// Shape abstract-superclass declaration. public abstract class Shape extends Object { // return area of shape; 0.0 by default public double getArea() { Keyword abstract return 0.0; declares class Shape as }

abstract class

// return volume of shape; 0.0 by default public double getVolume() { return 0.0; } // abstract method, overridden by subclasses public abstract String getName(); } // end abstract class Shape

Keyword abstract declares method getName as abstract method-See Next slides Example from Deitel & Deitel’s Book

 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

// Point.java // Point class declaration inherits from Shape. public class Point extends Shape { private int x; // x part of coordinate pair private int y; // y part of coordinate pair

Outline Point.java

// no-argument constructor; x and y default to 0 public Point() { // implicit call to Object constructor occurs here } // constructor public Point( int xValue, int yValue ) { // implicit call to Object constructor occurs here x = xValue; // no need for validation y = yValue; // no need for validation } // set x in coordinate pair public void setX( int xValue ) { x = xValue; // no need for validation }

 2003 Prentice Hall, Inc. All rights reserved.

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

// return x from coordinate pair public int getX() { return x; } // set y in coordinate pair public void setY( int yValue ) { y = yValue; // no need for validation }

Outline Point.java Lines 47-50 Override abstract method getName. Override abstract method getName.

// return y from coordinate pair public int getY() { return y; } // override abstract method getName to return "Point" public String getName() { return "Point"; } // override toString to return String representation of Point public String toString() { return "[" + getX() + ", " + getY() + "]"; }

 2003 Prentice Hall, Inc. } // end class Point

All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// Circle.java // Circle class inherits from Point. public class Circle extends Point { private double radius; // Circle's radius

Outline Circle.java

// no-argument constructor; radius defaults to 0.0 public Circle() { // implicit call to Point constructor occurs here } // constructor public Circle( int x, int y, double radiusValue ) { super( x, y ); // call Point constructor setRadius( radiusValue ); } // set radius public void setRadius( double radiusValue ) { radius = ( radiusValue < 0.0 ? 0.0 : radiusValue ); }

 2003 Prentice Hall, Inc. All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

// return radius public double getRadius() { return radius; }

Circle.java

// calculate and return diameter public double getDiameter() { return 2 * getRadius(); }

Lines 45-48 Override method getArea to return circle area.

// calculate and return circumference public double getCircumference() { return Math.PI * getDiameter(); }

Outline

Override method getArea to return circle area Otherwise not the circle area wiil be returned…

// override method getArea to return Circle area public double getArea() { return Math.PI * getRadius() * getRadius(); }

 2003 Prentice Hall, Inc. All rights reserved.

50 51 52 53 54 55 56 57 58 59 60 61 62

// override abstract method getName to return "Circle" public String getName() { Override return "Circle"; abstract }

method getName

Outline Circle.java

// override toString to return String representation of Circle Lines 51-54 Override abstract public String toString() method getName. { return "Center = " + super.toString() + "; Radius = " + getRadius(); } } // end class Circle

 2003 Prentice Hall, Inc. All rights reserved.

Another example… Example: Student.java, CompSciStudent.java, CompSciStudentDemo.java

/** The Student class is an abstract class that holds * general data about a student. Classes representing * specific types of students should inherit from * this class. */

public abstract class Student { private String name; // Student name private String idNumber; // Student ID private int yearAdmitted; // Year student was admitted public Student(String n, String id, int year) { name = n; idNumber = id; yearAdmitted = year; } /* toString method */ public String toString() { String str; str = "Name: " + name + "\nID Number: " + idNumber + "\nYear Admitted: " + yearAdmitted; return str; } /*The getRemainingHours method is abstract. * It must be overridden in a subclass. */ public abstract int getRemainingHours(); }

public class CompSciStudent extends Student { private final int MATH_HOURS = 20, CS_HOURS = 40, GEN_ED_HOURS = 60; private int mathHours, // Math hours taken csHours, // Comp. sci. hours taken genEdHours; // General ed hours taken public CompSciStudent(String n, String id, int year) { super(n, id, year); } public void setMathHours(int math) { mathHours = math; } public void setCsHours(int cs) { csHours = cs; } public void setGenEdHours(int genEd) { genEdHours = genEd; } public String toString() { String str; // To hold a string str = super.toString() + "\nMajor: Computer Science" + "\nMath Hours Taken: " + mathHours + "\nComputer Science Hours Taken: " + csHours + "\nGeneral Ed Hours Taken: " + genEdHours; return str; }

public int getRemainingHours() { int reqHours, // Total required hours remainingHours; // Remaining hours // Calculate the total required hours. reqHours = MATH_HOURS + CS_HOURS + GEN_ED_HOURS; // Calculate the remaining hours. remainingHours = reqHours - (mathHours + csHours + genEdHours); // Return the remaining hours. return remainingHours; } }

public class CompSciStudentDemo { public static void main(String[] args) { // Create a CompSciStudent object. CompSciStudent csStudent = new CompSciStudent("Jennifer Haynes", "167W98337", 2004); // Store values for math, CS, and General Ed hours. csStudent.setMathHours(12); csStudent.setCsHours(20); csStudent.setGenEdHours(40); // Display the student's data. System.out.println(csStudent); // Display the number of remaining hours. System.out.println("Hours remaining: " + csStudent.getRemainingHours()); } }

Output

Another example… Example: Instrument class can easily be turned into an abstract class

Instrument class

// Abstract classes and methods. import java.util.*; abstract class Instrument { int i; // storage allocated for each public abstract void play( ) ; public String what( ) { return "Instrument"; } public abstract void adjust(); } class Wind extends Instrument { public void play( ) { System.out.println("Wind.play()"); } public String what( ) { return "Wind"; } public void adjust( ) {} }

class Percussion extends Instrument { public void play() { System.out.println("Percussion.play()"); } public String what() { return "Percussion"; } public void adjust() {} } class Stringed extends Instrument { public void play() { System.out.println("Stringed.play()"); } public String what() { return "Stringed"; } public void adjust() {} } class Brass extends Wind { public void play() { System.out.println("Brass.play()"); } public void adjust() { System.out.println("Brass.adjust()"); } }

It’s helpful to create abstract classes and methods because they make the abstractness of a class explicit, and tell both the user and the compiler how it was intended to be used.

Interfaces (cont’ed Chapter 10.x) Design Abstraction and a way for controlling Multiple Inheritance/properties

Interfaces 

Interface is a conceptual entity similar to an Abstract class.  

Can contain only constants (final variables) abstract method(s) (no implementation) – 





Different from Abstract classes.

Used when a number of classes share a common interface. Each class should implement the interface.

Relatedness of types 

Consider the task of writing classes to represent 2D shapes such as Circle, Rectangle, and Triangle.



There are certain attributes or operations that are common to all shapes. perimeter area



- distance around the outside of the shape - amount of 2D space occupied by the shape

Every shape has these attributes, but each computes them differently.

Interfaces 





An interface is basically a kind of class—it contains methods and variables, but they have to be only abstract classes and final fields/variables.  Therefore, it is the responsibility of the class that implements an interface to supply the code for methods. A class can implement any number of interfaces, but cannot extend more than one class at a time.

Therefore, interfaces are considered as an informal way of controlling multiple inheritance in Java.

Implementing an interface 

A class can declare that it implements an interface. 

This means the class contains an implementation for each of the abstract methods in that interface. (Otherwise, the class will fail to compile.)



Implementing an interface, general syntax: public class implements { ... } 

Example: public class Bicycle implements Vehicle { ... } (What must be true about the Bicycle class for it to compile?)

Declaration.. interface Name { void method1(int param1,…); }

access class classname [extends superclass] [implements interface [,interface...]] { // class-body } See an example in the next slide

An example of using an interface interface Fruit { public boolean hasAPeel(); //has a peel must be implemented in any class implementing Fruit

//methods in interfaces must be public } interface Vegetable { public boolean isARoot(); //is a root must be implemented in any class implementing Vegetable //methods in interfaces must be public

}

example of using an interface class Tomato implements Fruit, Vegetable { boolean peel = false; boolean root = false; public Tomato() {} public boolean hasAPeel() //must have this method, // because Fruit declared it { return peel; } public boolean isARoot() //must have this method, // because Vegetable declared it { return root; }

Interface 

Actually Interfaces describe the methods that should be implemented in the new class 

Like the spine that a class must follow

Interface vs. abstract class 





Interface is like a template-If you need to change your design, make it an interface. Abstract classes provide default behavior. Abstract classes are excellent candidates inside of application frameworks since they provide default behavior. behavior Interface has to have body of the method and the method is to be used by the classes inheriting/ implementing this interface. Whereas in the case of Abstract Class it can have declarations (Other than the abstract method) and it can be further extended in the classes inheriting the Abstract Class.

Interface vs. abstract class 

Abstract Class:  



A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.

Interface:  

Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.

1 2 3 4 5 6 7 8 9

// Fig. 10.18: Shape.java // Shape interface declaration. public interface public double public double public String

Shape { getArea(); getVolume(); getName();

} // end interface Shape

Classes that implement Shape must implement these methods

// calculate area // calculate volume // return shape name

Outline Shape.java Lines 5-7 Classes that implement Shape must implement these methods

 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

// Fig. 10.19: Point.java // Point class declaration implements interface Shape. public class Point extends Object implements Shape { private int x; // x part of coordinate pair private int y; // y part of coordinate pair // no-argument constructor; x and y default to 0 public Point() Point implements { // implicit call to Object constructor occurs here }

Outline Point.java Line 4 Point implements interface Shape interface Shape

// constructor public Point( int xValue, int yValue ) { // implicit call to Object constructor occurs here x = xValue; // no need for validation y = yValue; // no need for validation } // set x in coordinate pair public void setX( int xValue ) { x = xValue; // no need for validation }

 2003 Prentice Hall, Inc. All rights reserved.

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

// return x from coordinate pair public int getX() { return x; }

Outline Point.java

// set y in coordinate pair public void setY( int yValue ) { y = yValue; // no need for validation } // return y from coordinate pair public int getY() { return y; }

 2003 Prentice Hall, Inc. All rights reserved.

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

// declare abstract method getArea public double getArea() { return 0.0; } // declare abstract method getVolume public double getVolume() { return 0.0; }

Outline Point.java Lines 47-59 Implement methods specified Implement methods by interface Shape specified by interface Shape

// override abstract method getName to return "Point" public String getName() { return "Point"; } // override toString to return String representation of Point public String toString() { return "[" + getX() + ", " + getY() + "]"; } } // end class Point

 2003 Prentice Hall, Inc. All rights reserved.

Extending Interfaces  

Like classes, interfaces can also be extended. The new sub-interface will inherit all the members of the superinterface in the manner similar to classes. This is achieved by using the keyword extends as follows:

interface InterfaceName2 extends InterfaceName1 { // Body of InterfaceName2 }

Inheritance and Interface Implementation 

A general form of interface implementation: class ClassName extends SuperClass implements InterfaceName [, InterfaceName2, …] { // Body of Class }



This shows a class can extended another class while implementing one or more interfaces. It appears like a multiple inheritance (if we consider interfaces as special kind of classes with certain restrictions or special features). Many interfaces could be implemented

Student Assessment Example (You need to know diagram creation) 

Consider a university where students who participate in the national games or Olympics are given some grace marks. Therefore, the final marks awarded = Exam_Marks + Sports_Marks. A class diagram representing this scenario is as follow: Student

Sports

extends Exam extends Results

implements

Software Implementation class Student { // student no and access methods } interface Sport { // sports grace marks (say 5 marks) and abstract methods } class Exam extends Student { // example marks (test1 and test 2 marks) and access methods } class Results extends Exam implements Sport { // implementation of abstract methods of Sport interface // other methods to compute total marks = test1+test2+sports_grace_marks; // other display or final results access methods }

Interfaces and Software Engineering 

Interfaces, like abstract classes and methods, provide templates of behaviour that other classes are expected to implement.



Separates out a design hierarchy from implementation hierarchy. This allows software designers to enforce/pass common/standard syntax for programmers implementing different classes. 



Pass method descriptions, not implementation

Java allows characteristics for inheritance from only a single superclass. Interfaces allow class mixing.



Classes implement interfaces.

Class/Relation Diagram An exercise might be like this: Write the Java code of the following diagram…

Two ways that a class can implement multiple interfaces 

// : c08:MultiInterfaces.java // Two ways that a class can implement multiple interfaces. // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 // www.BruceEckel.com. See copyright notice in CopyRight.txt.

interface A { } interface B { } class X implements A, B { } class Y implements A { B makeB() { // Anonymous inner class: return new B() { }; } } public class MultiInterfaces { static void takesA(A a) { } static void takesB(B b) { } public static void main(String[] args) { X x = new X(); Y y = new Y(); takesA(x); takesA(y); takesB(x); takesB(y.makeB()); } } ///:~

So all should be clarified like… 

Abstract classes have all characteristics of a spine / skeleton 



We can also add some extra “bones”…

Interfaces are the basic templates that a class might or should follow

Superclasses and Subclasses Shape

TwoDimensionalShape Circle



Square

Triangle

ThreeDimensionalShape Sphere

Cube

Tetrahedron

Using inheritance 

Use keyword extends

class TwoDimensionalShape extends Shape{ ... }  private members of superclass not directly accessible to subclass  All other variables keep their member access

Keep it in mind for modeling process required for your project

Remember General Programming Considerations ■ Avoid designing a class that has no methods. ■ Use design patterns. ■ Reduce the visibility of things as much as possible. ■ Use overloading rather than logic. ■ Avoid long argument lists.