Title: Inheritance
1Inheritance
- Creating new classes from existing classes.
- CSC 313 JavaLinda M. Hicks
2Derived Classes
- Defining a new class based on an existing class
is called derivation. - The new class or derived class, is referred to
as a direct sub-class of the class from which it
is derived. - The original class is called a base class
because it forms the base for the definition of
the derived class.
3Derived Classes
- The original class is also referred to as a
super-class of the derived class. - A super-class can itself be a sub-class of
another class, which will then be an indirect
super-class of the lowest derived class. - This is illustrated in the next slide.
4Derived Classes
5The Universal Super-Class
- All the classes that you define are sub-classes
by default, of the standard class, Object. - Object is a super-class of every class.
- You never need to specify the class Object as a
base in the definition of your classes - it
happens automatically.
6The Universal Super-Class
- A variable of type Object can hold an object of
any class. - This is useful when you want to write a method
that needs to handle objects of unknown type. - You can use a variable of type Object as a
parameter to a method to receive an object, and
then include code in the method that figures out
what kind of object it actually it is.
7Object Super-Class
- Your classes will inherit members from the class
Object, which are all methods. - Of these seven methods are public, and two are
protected. - These public methods include
- toString()
- getClass()
- equals()
- hashCode()
- notify()
- notifyAll()
- wait()
8Object Methods Inherited
9Object Methods Inherited
10What Does Inheritance Mean?
- The inclusion of members of the base class in a
derived class so that they are accessible in that
derived class is called class inheritance. - An inherited member of a derived class is a full
member of that class. - However, not all members of the base class are
necessarily accessible in the derived class. That
depends on the member's access attributes.
11Access Specifier Keywords
- public grants unlimited access to all classes.
- private allows no access to the member from
outside the class.
12Access Specifier Keywords
- protected gives unlimited access to classes in
the same package. - It also allows all subclasses to access methods,
regardless of whether the subclasses are in the
same package. - A subclass from a different package can inherit
fields but not access them directly. - A class that is in a different package and is
not a subclass has no access to protected fields.
13Access Specifier Keywords
- There is no keyword for default access.
- This access is sometimes called package access
and applies when the access specifier is omitted. - Package access grants unlimited access to classes
in the same package, but no access to classes
outside the package.
14Java Access Specifiers
15Inheriting Data Members
- The next diagram illustrates access attributes.
- It shows what happens when
- the sub-class is defined in the same package as
the base class, and - when the sub-class is defined in a package
different from that containing the base class.
16Java Access Illustrated
17Objects of a Derived Class
- A derived class extends a base class.
- Inheritance is about what members of the base
class are accessible in a derived class, not what
members of the base class exist in a derived
class object. - An object of a sub-class will contain
- plus any new members defined in the derived class
as illustrated in the next slide. - all the members of the original base class,
18Objects of a Derived Class
19Objects of a Derived Class
- The base members are all there - you just can't
access some of them in the methods that you
define for the derived class. - The base class methods which are inherited in a
derived class can access all the base class
members, including those that are not inherited.
20Objects of a Derived Class
- Though the base class constructors are not
inherited in your derived class, you can still
call them to initialize the base class members,
using the Super reference. - If you don't call a base class constructor from
your derived class constructor, the compiler will
try to arrange to do it for you.
21Simple Example.
- Lets look at a simple example. Suppose we have
defined a class to represent an animal
22public class Animal private String
type public Animal (String aType)
// constructor type new
String(aType) public void
show() System.out.println("This
is a " type)
23Animal Class Example
- We now want to create another class based on
the class Animal to define dogs. - We can do this immediately, without affecting
the definition of the class Animal. - We could write the definition of the class Dog
as
24public class Dog extends Animal //
constructors public Dog (String aName)
super ("Dog") // Call the base
constructor name aName
// Supplied name breed "Unknown"
// Default breed value public Dog
(String aName, String aBreed)
super ("Dog") // Call the base
constructor name aName //
Supplied name breed aBreed //
Supplied breed private String
name // Name of a Dog! private String
breed // Dog breed
25Derived Class Dog
- Use the keyword extends in the definition of a
sub-class to identify the name of the
super-class. - The class Dog will only inherit the method show()
from the class Animal, since the private data
member and the constructor cannot be inherited.
- Two new instance variables added - name, to hold
the name of the particular dog, and breed, to
store the kind of dog.
26Derived Class Constructors
- The sub-class has two constructors, one that
takes the name of a dog, and the other that
accepts both a name and the breed of the Dog
object. - We need to make sure that the private base class
member type, is properly initialized. - The statement in the derived class constructor
that does this is super("Dog")
27Test Dog Class with code
- public class TestDerived
-
- public static void main (String args)
-
- Dog aDog new Dog ("Fido", "Chihuahua")
- Dog starDog new Dog("Lassie")
- aDog.show()
- starDog.show()
-
-
-
28Test Output
- This is a Dog
- This is a Dog
- All dogs have the same output because they all
use the same derived method show() from the
animal class. - A dog has added features that can be shown. To
display these, we can override the method show ()
29Overriding a Base Class Method
- // Show a dog's details
- public void show()
-
- super.show() // Call the base method
- System.out.println ("It's " name " the "
breed) -
30Overriding a Base Class Method
- With this change to the example, the output
will now be - This is a Dog
- It's Fido the Chihuahua
- This is a Dog
- It's Lassie the Unknown
31Overriding Base Class Methods
- The show() method called with a Dog object,
overrides the base class method because it has
the same signature. - The signature of a method is determined by its
name and the parameter list. - The keyword super is used to identify the base
class version of show() that is hidden by the
derived class version.
32Overriding Base Class Methods
- The overridden show() method must be declared as
public. - When you override a base class method, you
cannot change the access attributes of the new
version of the method to be more stringent than
that of the base class method that it overrides.
33What is polymorphism?
- The word polymorphism means the ability to assume
several different forms or shapes. - In programming terms it means the ability of a
single variable to call different methods,
depending on what the variable contains.
34Features of Polymorphism
- Polymorphism involves using a variable of a
single type, to store objects of any kind derived
classes. - An example of this might be might be using a
variable of type Dog to store objects of type
Spaniel, type Chihuahua or type Collie, where
these are all classes derived from Dog.
35Polymorphism features
- Secondly, it involves the automatic use of the
object stored in the base class variable to
select a method from one of the derived classes,
dependent on the object's class. - The kind of object stored is not known until the
program executes, so the choice of which class's
method to execute is made dynamically, when the
program is running. The variable of type Dog can
do different things, depending on what kind of
object (breed of dog) it contains.
36Sub-class assignments in Java
- A crucial feature of polymorphism is the ability
to assign an object of a sub-class to a variable
that you have declared as being of the base class
type. - If you declare the variable
- Animal theAnimal // Declare an animal
variable - You can make this refer to an object of any of
the sub-classes of the class Animal.
37Sub-class assignments in Java
- For example, you could use it to reference an
object of type Dog - theAnimal new Dog("Rover")
- This object casting applies quite generally. You
can make a variable of a base class point to an
object of any class that you have derived,
directly or indirectly, from the base.
38Polymorphism Illustrated
- To illustrate polymorphism, we can add a new
method to the class Dog which will output the
sound a Dog makes. - And we can add a couple of new sub-classes which
will relate to some other kinds of animals.
39 First of all we will enhance the class Dog
public class Dog extends Animal //
Rest of the class as before... // A
barking method public void sound()
System.out.println("Woof Woof")
40Derive class Cat from the class Animal
public class Cat extends Animal
private String name // Name of a cat
private String breed // cat breed //
cat constructors public Cat (String
aName) super("Cat") //
Call the base constructor name aName
// Supplied name breed
"Unknown" // Default breed value
41 // derived Cat class continued public
Cat (String aName, String aBreed)
super("Cat") // Call the base
constructor name aName //
Supplied name breed aBreed //
Supplied breed // Show a cat's
details public void show()
super.show() // Call the base method
System.out.println("It's " name " the "
breed) // A miaowing method
public void sound()
System.out.println("Miiaooww")
// end class Cat
42Derived Class Duck
- public class Duck extends Animal
-
- private String name // Ducky name
- private String breed // Duck breed
- // constructors
- public Duck(String aName)
- super("Duck") // Call the base
constructor - name aName // Supplied name
- breed "Unknown" // Default breed
value -
-
43 // Derived class Duck continued public
Duck (String aName, String aBreed)
super("Duck") // Call the base
constructor name aName //
Supplied name breed aBreed //
Supplied breed // Show a duck's
details public void show()
super.show() // Call the base
method System.out.println("It's " name
" the " breed) // A quacking
method public void sound()
System.out.println ("Quack quackquack")
44- To show how polymorphism works, we need to
make one change to the class Animal. - To select a method sound() dynamically, the
sound method needs to be a member of the base
class. We can add a content-free version of
sound() to the class Animal -
- class Animal
- // Rest of the class as before...
- // Dummy method to be implemented in //
the derived classes - public void sound()
-
45TryPolymorphism Test Program
public class TryPolymorphism
public static void main (String args)
// Create an array of three different
animals Animal theAnimals
new Dog ("Rover",
"Poodle"), new
Cat ("Max", "Abyssinian"),
new Duck ("Daffy","Aylesbury")
Animal petChoice //
Choice of pet
46 //TryPolymorphism continued //
Make five random choices of pet for(int
i 0 i lt 5 i) //
Create a random index from 0 to
theAnimals.length-1 int index
(int)(theAnimals.lengthMath.random() - 0.001)
petChoice theAnimals index //
Pick from the array System.out.println(
"\nYour choice") petChoice.show()
// Display the details
petChoice.sound() // Get the
pet's reaction // end for loop
// end main // end TryPolymorphism
47Possible Program Output
- Your choiceThis is a Dog It is a
Poodle called RoverWoof Woof - Your choice
- This is a Dog
- It is a Poodle called Rover
- Woof Woof
- Your choice
- This is a Duck
- It is a Aylesbury called Daffy
- Quack quackquack
-
- Your choice
- This is a Duck
- It is a Aylesbury called Daffy
- Quack quackquack
- Your choice
- This is a Cat
- It is a Abyssinian called Max
- Miiaooww
48Multiple Levels of Inheritance
- There is nothing to prevent a derived class being
used as a base class. For example, we could
derive a class Spaniel from the class Dog. - Then we could add a Spaniel object to the array
theAnimals in the TryPolymorphism.java program,
by changing the statement to - Animal theAnimals
- new Dog("Rover",
"Poodle"), - new Cat("Max",
"Abyssinian"), - new
Duck("Daffy","Aylesbury"), - new Spaniel("Fido")
49Class Spaniel derived from Dog
- class Spaniel extends Dog
- public Spaniel (String aName)
- super (aName, "Spaniel")
- // end constructor
- public void show()
- System.out.println("Spaniel show method
called") - super.show() // Call the base (Dog)
method, show() - // end show()
- // end Spaniel
50Sample Program Output
- This is a Turtle
- Your choice
- This is a Dog
- Woof Woof
- Your choice
- This is a Cat
- It's Max the Abyssinian
- Miiaooww
- Your choice
- This is a Duck
- It's Daffy the Aylesbury
- Quack quackquack
- Your choice
- Spaniel show method called
- This is a Dog
- Woof Woof
51Java uses Dynamic Method Dispatchto implement
polymorphism.
52Polymorphism
- When you have several sub-classes of a common
base class, each containing a definition of a
method with the same signature as a given base
class method, polymorphism enables you to defer
the decision about which of these methods is to
be called for a class variable until runtime. - This is sometimes referred to as dynamic, or
late, binding, because the method to be executed
is selected dynamically when you run your program.
53Polymorphism
- Class inheritance allows Java to support the
mechanism called polymorphism. - Polymorphism is fundamental to the idea of
object-oriented programming. - Normally, the method which is to be executed for
a particular object is fixed by the compiler, so
that it is always the same whenever you execute
your program. This is often referred to as
static, or early, binding.
54Using the final Modifier
- The keyword final has three uses.
- 1. To create the equivalent of a named constant,
as aSize in TryPolymorphism.java final
int aSize 4 - 2.You can also apply this to a method to prevent
a sub-class from overriding a method in your
class. When this is the case, simply declare that
method as final. Any attempt to override a final
method in a sub-class will result in the compiler
flagging the new method as an error.
55Using the final Modifier
- 3. If you declare a class as final, you prevent
any sub-classes from being derived from it. - To declare the class Spaniel as final, you
would define it as - public final class Spaniel
- // Definition as before...
-
56To Be Continued.