Inheritance
Inheritance
with Java
Inheritance
Inheritance
Superclass Subclass
Circle Cylinder
UML Diagram -radius
-length
+getRadius
+setRadius +getLength
+findArea +setLength
+findVolume
Creating a Subclass
Creating a subclass extends properties and
methods from the superclass. You can also:
! Add new properties
! Add new methods
! Override the methods of the superclass
Cylinder Class
Example 8.1
Testing Inheritance
l Objective: Create a Cylinder object and
explore the relationship between the
Cylinder and Circle classes.
TestCylinder Run
Using the Keyword super
The keyword super refers to the superclass
of the class in which super appears. This
keyword can be used in two ways:
l To call a superclass constructor
l To call a superclass method
Example 8.2
Overriding Methods in the Superclass
Cylinder
TestOverrideMethods Run
The Object Class
l The Object class is the root of all Java
classes.
newObject = someObject.clone();
pacakge p1 pacakge p2
class C3 class C4
C1 c1; C1 c1;
c1.x can be read or c1.x cannot be read
modified nor modified
The final Modifier
l The final class cannot be extended:
final class Math
{...}
+getWidth(): double
+setWidth(width: double): void
+getLength(): double
+setLength(length: double): void
TestPolymorphism Run
Casting Objects
It is always possible to convert a subclass to a
superclass. For this reason, explicit casting can be
omitted. For example,
Circle myCircle = myCylinder
is equivalent to
Circle myCircle = (Circle)myCylinder;
Casting from
Superclass to Subclass
Explicit casting must be used when casting an
object from a superclass to a subclass. This
type of casting may not always succeed.
TestCasting Run
Interfaces
lWhat Is an Interface?
lCreating an Interface
lImplementing an Interface
lWhat is Marker Interface?
Creating an Interface
modifier interface InterfaceName
{
constants declarations;
methods signatures;
}
Example of Creating an Interface
TestInterface Run
Interfaces vs. Abstract Classes
Interface1_2 Interface2_2
TestCloneable Run
Example 8.6
Cloning Objects, cont.
Memory
c1: CloneableCircle 5
radius = 5
creator = reference creator: Name
{"Yong", ‘D’, "Liang")
firstname = "Yong"
mi = ‘D’
firstname = "Liang"
c2: CloneableCircle 5
radius = 5
creator = reference
{"Yong", ‘D’, "Liang")
Inner Classes
Inner class: A class is a member of another
class.
Advantages: In some applications, you can
use an inner class to make programs
simple.
l An inner class can reference the data and
methods defined in the outer class in which
it nests, so you do not need to pass the
reference of the outer class to the
constructor of the innerShowInnerClass
class.
Inner Classes (cont.)
l Inner classes can make programs simple
and concise. As you see, the new class is
shorter and leaner. Many Java development
tools use inner classes to generate
adapters for handling events.
l An inner class is only for supporting the
work of its containing outer class, and it
cannot be used by other classes.