Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F...

34
Chapter 6 Class Inheritance Superclasses and Subclasses Superclasses and Subclasses Keywords: super Keywords: super Overriding methods Overriding methods The Object Class The Object Class Modifiers: protected, final and Modifiers: protected, final and abstract abstract Polymorphism and Object Casting Polymorphism and Object Casting Interfaces Interfaces Inner Classes Inner Classes Program Development and Class Design Program Development and Class Design

Transcript of Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F...

Chapter 6 Class Inheritance

Superclasses and SubclassesSuperclasses and Subclasses Keywords: superKeywords: super Overriding methodsOverriding methods The Object ClassThe Object Class Modifiers: protected, final and abstractModifiers: protected, final and abstract Polymorphism and Object Casting Polymorphism and Object Casting InterfacesInterfaces Inner ClassesInner Classes Program Development and Class DesignProgram Development and Class Design

Superclasses and Subclasses

Circle-radius

+getRadius+setRadius+findArea

Cylinder

-length

+getLength+setLength+findVolume

SubclassSuperclass

UML Diagram

Creating a Subclass

Creating a subclass extends properties and Creating a subclass extends properties and methods from the superclass. You can also:methods from the superclass. You can also:

Add new propertiesAdd new properties

Add new methodsAdd new methods

Override the methods of the superclassOverride the methods of the superclass

Cylinder ClassCylinder Class

Example 6.1Testing Inheritance

Objective: Create a Objective: Create a CylinderCylinder object and object and explore the relationship between the explore the relationship between the CylinderCylinder and and CircleCircle classes. classes.

TestCylinderTestCylinder RunRun

Using the Keyword super

To call a superclass constructorTo call a superclass constructor

To call a superclass methodTo call a superclass method

The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways:

Example 6.2 Overriding Methods in the Superclass

The Cylinder class overrides the The Cylinder class overrides the findArea() method defined in the findArea() method defined in the Circle class.Circle class.

TestModifyingMethodsTestModifyingMethods RunRun

The Object Class The The ObjectObject class is the root of all Java class is the root of all Java

classes.classes.

The The toString()toString() method returns a string method returns a string representation of the object.representation of the object.

The The equals()equals() method compares the method compares thecontents of two objects. contents of two objects.

The The clone()clone() method copy objects method copy objects

The protected Modifier

The protected modifier can be applied on The protected modifier can be applied on data and methods in a class. data and methods in a class.

A protected data or a protected method in A protected data or a protected method in a public class can be accessed by any a public class can be accessed by any class in the same package or its class in the same package or its subclasses, even if the subclasses are in a subclasses, even if the subclasses are in a different package.different package.

The protected Modifier, cont.

pacakge p1

class C1

protected int x

class C3

C1 c1;c1.x can be read ormodified

pacakge p2

class C2 extends C1

x can be read ormodified in C2

class C4

C1 c1;c1.x cannot be readnor modified

The final Modifier

The finalThe final class cannot be extended: class cannot be extended: final class Math {...}final class Math {...}

The finalThe final variable is a constant: variable is a constant: final static double PI = 3.14159;final static double PI = 3.14159;

The finalThe final method cannot be method cannot bemodified by its subclasses.modified by its subclasses.

The abstract Modifier The abstractThe abstract class class

Cannot be instantiatedCannot be instantiatedShould be extended and Should be extended and

implemented in subclassesimplemented in subclasses

The abstractThe abstract method methodMethod signature withoutMethod signature without

implementationimplementation

Abstract Classes

Circle-radius

+getRadius+setRadius

Cylinder

-length

+getLength+setLength+findVolume

GeometricObject

-color-weight

+getColor+setColor+getWeight+setWeight+findArea+findPerimeter

Object

Rectangle

-width-length

+getWidth+setWidth+getLength+setLength

Notation:The abstract class name andthe abstract method namesare italicized in the UML.

GeometricObjectGeometricObject

CircleCircle CylinderCylinder

RectangleRectangle

Polymorphism and Dynamic Binding

Polymorphism refers to the ability to Polymorphism refers to the ability to determine at runtime which code to determine at runtime which code to run, given multiple methods with the run, given multiple methods with the same name but different operations in same name but different operations in the same class or in different classes. the same class or in different classes. This ability is also known as This ability is also known as dynamic dynamic bindingbinding..

Example 6.3 Testing Polymorphism

Objective: Objective: This example creates two geometric This example creates two geometric objects: a circle, and a rectangle, invokes the objects: a circle, and a rectangle, invokes the equalAreaequalArea method to check if the two objects method to check if the two objects have equal area, and invokes the have equal area, and invokes the displayGeometricObjectdisplayGeometricObject method to display the method to display the objects.objects.

TestPolymorphismTestPolymorphism RunRun

Casting Objects

It is always possible to convert a subclass to a It is always possible to convert a subclass to a superclass. For this reason, explicit casting can be superclass. For this reason, explicit casting can be omitted. For example,omitted. For example,

Circle myCircle = myCylinderCircle myCircle = myCylinder

is equivalent tois equivalent to

Circle myCircle = (Circle)myCylinder;Circle myCircle = (Circle)myCylinder;

Casting fromSuperclass to Subclass

Explicit casting must be used when casting an Explicit casting must be used when casting an object from a superclass to a subclass. This object from a superclass to a subclass. This type of casting may not always succeed.type of casting may not always succeed.

Cylinder myCylinder = (Cylinder)myCircle;Cylinder myCylinder = (Cylinder)myCircle;

The instanceof Operator

Use the Use the instanceofinstanceof operator to test whether an operator to test whether an object is an instance of a class:object is an instance of a class:

Circle myCircle = new Circle();Circle myCircle = new Circle();

if (myCircle instanceof Cylinder) { if (myCircle instanceof Cylinder) { Cylinder myCylinder = (Cylinder)myCircle;Cylinder myCylinder = (Cylinder)myCircle; ......}}

Example 6.4Casting Objects

This example creates two geometric This example creates two geometric objects: a circle, and a cylinder, invokes the objects: a circle, and a cylinder, invokes the displayGeometricObjectdisplayGeometricObject method to display method to display the objects. The the objects. The displayGeometricObjectdisplayGeometricObject displays the area and perimeter if the object displays the area and perimeter if the object is a circle, and displays area and volume if is a circle, and displays area and volume if the object is a cylinder. the object is a cylinder.

TestCastingTestCasting RunRun

Interfaces

What Is an Interface?What Is an Interface?

Creating an InterfaceCreating an Interface

Implementing an InterfaceImplementing an Interface

What is Marker Interface?What is Marker Interface?

Creating an Interface

modifier interface InterfaceName { modifier interface InterfaceName { constants declarations;constants declarations; methods signatures;methods signatures;}}

Example of Creating an Interface

// // This interface is defined in This interface is defined in

// java.// java.lang packagelang package

public interface Comparable {public interface Comparable {

public int compareTo(Object o);public int compareTo(Object o);

}}

Generic max Methodpublic class Max {public class Max {

// Return the maximum between two objects// Return the maximum between two objects

public static Comparable max (Comparable o1, public static Comparable max (Comparable o1, Comparable o2) {Comparable o2) {

if (o1.compareTo(o2) > 0)if (o1.compareTo(o2) > 0)

return o1;return o1;

elseelse

return o2;return o2;

}} }}

Example 6.5 Using Interfaces

Objective: Use the max method to find a Objective: Use the max method to find a maximum circle between two circles maximum circle between two circles and a maximum cylinder between two and a maximum cylinder between two cylinders. cylinders.

Example 6.5, cont.

TestInterfaceTestInterface RunRun

Circle-

CylinderGeometricObject-

java.lang.Comparable

compareTo

Notation:The interface class name andthe method names areitalicized. The dashed linesand dashed hollow trianglesare used to point to theinterface.

ComparableCircle

-ComparableCylinder

-

Interfaces vs. Abstract Classes

In an interface, the data must be In an interface, the data must be constants; an abstract class can have all constants; an abstract class can have all types of data.types of data.

Each method in an interface has only a Each method in an interface has only a signature without implementation; an signature without implementation; an abstract class can have concrete abstract class can have concrete methods. An abstract class must contain methods. An abstract class must contain at least one abstract method or inherit at least one abstract method or inherit from another abstract method.from another abstract method.

Interfaces vs. Abstract Classes, cont.

Since all the methods defined in an Since all the methods defined in an interface are abstract methods, interface are abstract methods, Java does not require you to put the Java does not require you to put the abstract modifier in the methods in abstract modifier in the methods in an interface, but you must put the an interface, but you must put the abstract modifier before an abstract abstract modifier before an abstract method in an abstract class.method in an abstract class.

Interfaces vs. Abstract Classes, cont.

Object Class1

Interface1Interface1_1

Interface1_2

Class2

Interface2_1

Interface2_2

The Cloneable Interfaces

public interface Cloneable { public interface Cloneable {

}}

Marker Interface: An empty interface.A marker interface does not contain constants or

methods, but it has a special meaning to the Java system. The Java system requires a class to implement the Cloneable interface to become cloneable.

Example 6.6 Cloning Objects

Objective: uses the Objective: uses the CloneableCloneable interface interface to mark classes cloneable and uses the to mark classes cloneable and uses the cloneclone method to copy objects. method to copy objects.

TestCloneableTestCloneable RunRun

Inner Classes

Inner class: A class is a member of another Inner class: A class is a member of another class.class.

Advantages: In some applications, you can Advantages: In some applications, you can use an inner class to make programs use an inner class to make programs simple.simple.

An inner class can reference the data and An inner class can reference the data and methods defined in the outer class in which methods defined in the outer class in which it nests, so you do not need to pass the it nests, so you do not need to pass the reference of the outer class to the reference of the outer class to the constructor of the inner class.constructor of the inner class.

ShowInnerClassShowInnerClass

Inner Classes (cont.) Inner classes can make programs simple Inner classes can make programs simple

and concise. As you see, the new class is and concise. As you see, the new class is shorter and leaner. Many Java shorter and leaner. Many Java development tools use inner classes to development tools use inner classes to generate adapters for handling events. generate adapters for handling events. Event-driven programming is introduced in Event-driven programming is introduced in Chapter 8, "Getting Started with Graphics Chapter 8, "Getting Started with Graphics Programming.”Programming.”

An inner class is only for supporting the An inner class is only for supporting the work of its containing outer class, and it work of its containing outer class, and it cannot be used by other classes.cannot be used by other classes.

Software Development Process

Requirement Specification

System Analysis

System Design

Implementation

Testing

Deployment

Maintenance

Class Design Guidelines Hide private data and private methods.Hide private data and private methods.

A property that is shared by all the A property that is shared by all the instances of the class should be instances of the class should be declared as a class property. declared as a class property.

Provide a public default constructor Provide a public default constructor and override the and override the equalsequals method and method and the the toStringtoString method defined in the method defined in the ObjectObject class whenever possible. class whenever possible.

Class Design Guidelines, cont. Choose informative names and Choose informative names and

followfollowconsistent styles.consistent styles.

A class should describe a single A class should describe a single entity or aentity or aset of similar operations. set of similar operations.

Group common data fields and Group common data fields and operations shared by other classes.operations shared by other classes.