chapter 7: class inheritance f superclasses and subclasses f keywords: super and this f overriding...
TRANSCRIPT
Chapter 7: Class Inheritance
Superclasses and SubclassesSuperclasses and Subclasses Keywords: super and thisKeywords: super and this Overriding methodsOverriding methods The Object ClassThe Object Class Modifiers: protected, final and Modifiers: protected, final and
abstractabstract Casting Objects Casting Objects Numeric Wrapper ClassesNumeric Wrapper Classes InterfacesInterfaces Inner ClassesInner Classes Class Design GuidelinesClass Design Guidelines
Superclasses and Subclasses
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
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 7.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
Example 7.3 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.
Test Modifying MethodsTest Modifying Methods RunRun
The Keyword this
The keyword The keyword thisthis refers to the current refers to the current object.object.
The keyword can be used in two ways:The keyword can be used in two ways: To call a class constructor
To pass the current class as an argumentto a method
Example of Using this class Circle class Circle { private double radius;{ private double radius;
Circle(double radius) Circle(double radius) {{ this.radius = radius;this.radius = radius; }} Circle() Circle() {{ this(1.0); this(1.0); }}
public double findArea()public double findArea() { { return radius*radius*Math.PI;return radius*radius*Math.PI; }} }}
The Object Class The The ObjectObject class is the root of all Java classes. class is the root of all Java 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 protected Modifier
The protected modifier can be applied The protected modifier can be applied on data and methods in a class. on data and methods in a class.
A protected data or a protected A protected data or a protected method in a public class can be method in a public class can be accessed by any class in the same accessed by any class in the same package or its subclasses, even if the package or its subclasses, even if the subclasses are in a different package.subclasses are in a different package.
The final Modifier
The The finalfinal class cannot be extended: class cannot be extended: final class Math {...}final class Math {...}
The The finalfinal variable is a constant: variable is a constant: final static double PI = 3.14159;final static double PI = 3.14159;
The The finalfinal method cannot be method cannot bemodified by its subclasses.modified by its subclasses.
The abstract Modifier The The abstractabstract classclass
Cannot be instantiatedCannot be instantiatedShould be extended and Should be extended and
implemented in subclassesimplemented in subclasses
The The abstractabstract method methodMethod signature withoutMethod signature without
implementationimplementation
Casting Objects It is always possible to convert a subclass to a It is always possible to convert a subclass to a superclass.superclass. For this reason, explicit casting can be omitted. For this reason, explicit casting can be omitted. For example,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.object from a superclass to a subclass. This type of casting may not always succeed.This 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 7.4Casting Objects
Objective: Use implicit casting to assign Objective: Use implicit casting to assign circles and cylinders to an array and then use circles and cylinders to an array and then use explicit casting to access data and methods explicit casting to access data and methods in the objects when processing the array.in the objects when processing the array.
TestCastingTestCasting RunRun
Class Inheritance Hierarchy
Numeric Wrapper Classes BooleanBoolean
CharacterCharacter
ShortShort
ByteByte
IntegerInteger
LongLong
FloatFloat
DoubleDouble
The Integer Classand The Double Class ConstructorsConstructors
Class Constants Class Constants MAX_VALUEMAX_VALUE, , MIN_VALUEMIN_VALUE
Conversion MethodsConversion Methods
Class Design Guidelines Hide private data and private methods.Hide private data and private methods.
Choose informative names and followChoose informative names and followconsistent styles.consistent styles.
A class should describe a single entity or aA class should describe a single entity or aset of similar operations. set of similar operations.
Group common data fields and operations Group common data fields and operations shared by other classes.shared by other classes.
Example 7.5Designing Abstract Classes
Objective: This example gives a generic class Objective: This example gives a generic class for matrix arithmetic. This class implements for matrix arithmetic. This class implements matrix addition and multiplication common for matrix addition and multiplication common for all types of matrices.all types of matrices.
GenericMatrixGenericMatrix
Example 7.6Extending Abstract Classes
Objective: This example gives two programs Objective: This example gives two programs that utilize the GenericMatrix class for integer that utilize the GenericMatrix class for integer matrix arithmetic and rational matrix matrix arithmetic and rational matrix arithmetic.arithmetic.
TestIntegerMatrixTestIntegerMatrix RunRun
TestRationalMatrixTestRationalMatrix RunRun
Interfaces
What Is an Interface?What Is an Interface?
Creating an InterfaceCreating an Interface
Implementing an InterfaceImplementing an Interface
Creating an Interface
modifier interface InterfaceNamemodifier interface InterfaceName{ { constants declarations;constants declarations; methods signatures;methods signatures;}}
Example of Creating an Interfacepublic interface CompareObjectpublic interface CompareObject{{ public static final int LESS = -1;public static final int LESS = -1;
public static final int EQUAL = 0;public static final int EQUAL = 0;public static final int GREATER = 1;public static final int GREATER = 1;
public int compare(CompareObject otherObject);public int compare(CompareObject otherObject);}}
Example 7.7 Using Interfaces
Objective: Use the generic sorting method Objective: Use the generic sorting method defined in the CompareObject interface to defined in the CompareObject interface to sort an array of circles in increasing order of sort an array of circles in increasing order of their radii and an array of cylinders in their radii and an array of cylinders in increasing order of their volumes. increasing order of their volumes.
Example 7.9 (cont.)
TestSortCircleCylinderTestSortCircleCylinder RunRun
Inner Classes
Inner class: A class is a member of another class.Inner class: A class is a member of another class.
Advantages: In some applications, you can use an Advantages: In some applications, you can use an inner class to make programs simple.inner class to make programs 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 it methods defined in the outer class in which it nests, so you do not need to pass the reference nests, so you do not need to pass the reference of the outer class to the constructor of the inner of the outer class to the constructor of the inner class.class.
Inner Classes (cont.) Inner classes can make programs simple and Inner classes can make programs simple and
concise. As you see, the new class is shorter concise. As you see, the new class is shorter and leaner. and leaner.
Many Java development tools use inner Many Java development tools use inner classes to generate adapters for handling classes to generate adapters for handling events. Event-driven programming is events. Event-driven programming is introduced in Chapter 8, "Getting Started with introduced in Chapter 8, "Getting Started with Graphics Programming.”Graphics Programming.”
An inner class is only for supporting the work of An inner class is only for supporting the work of its containing outer class, and it cannot be used its containing outer class, and it cannot be used by other classes.by other classes.