Sie sind auf Seite 1von 37

INHERITANCE

Material from Dr. Snyder's lecture notes for CS 211


Example
public class Person {
public String name;
public int age;
}

public class Student extends Person{


public int studentID;
}

A Person object has 2 instance variables: name and age


A Student object has 3 instance variables: name, age, studentID
the Student class is a subclass of the Person class.
Material from Dr. Snyder's lecture notes for CS 211
What is Inheritance?
Inheritance lets once class get all
definitions from another for free
then it may add or modify definitions
(but not remove)
Defines a parent-class / child-class
relationship.
Defines a subtype relationship.

Material from Dr. Snyder's lecture notes for CS 211


Why do we want inheritance?
Gives us a very powerful means for code reuse
retype as little as possible, always!

Gives us a powerful feature: subtyping.


allows for specialization
allows one definition to work on multiple
related types

Material from Dr. Snyder's lecture notes for CS 211


Reuse benefits

modifications are centralized

get to use code we've already tested (don't rewrite, reuse the
solution directly)

Properly designed inheritance relationships can contribute


greatly to the elegance, maintainabilty, and reuse of the software

lets compiler know types are related


makes our code more flexible in a controlled way

Material from Dr. Snyder's lecture notes for CS 211


Sub-Classes
"A Class is a Type" "A Sub-Class is a Sub-Type"

What is a sub-type? Think of sets:


Integers: {,-2, -1, 0, 1, 2, }
Naturals: {0, 1, 2, }

every single Natural value is also an Integer value:


Natural is a subset of Integer. " Natural Integer "

We know some subtypes from math:


Bit Natural Integer Rational Real Complex
Material from Dr. Snyder's lecture notes for CS 211
Example Hierarchies

We know some other subtype relationships:


Humans Primates Mammals Animals
Freshmen Undergrads Students People
squares rectangles parallelograms shapes
SUVs Trucks Vehicles Machines

A type is (basically) a set of values, so a subtype


contains a subset of the superset's values.

Material from Dr. Snyder's lecture notes for CS 211


Identifying Hierarchies
Look for similarity in structure
Look for more specific versions of things
(Mammal, Primate; Bird, Penguin)
Think of unneeded-but-connecting things, like
Mammal, Truck, Student, Container, etc.
some def's could be placed in these intermediate places
Remember: Classes define what data/behavior is
common between separate classes.
you might still be creating many objects of type
Parallelogram and of type Rectangle, but their definitions
could share side1 and side2 variables.
Material from Dr. Snyder's lecture notes for CS 211
Clarification:
extending a class instantiating object
Extending a class:
making one 'blueprint' from another.
creating new class, but no objects created
just yet.

Instantiating an object:
using a class 'blueprint' to make an object.
Class def'ns used, but not made here.
object is being created here.
Material from Dr. Snyder's lecture notes for CS 211
Example
public class Person {
public String name;
public int age;
}

public class Student extends Person{


public int studentID;
}

A Person object has 2 instance variables: name and age


A Student object has 3 instance variables: name, age, studentID
the Student class is a subclass of the Person class.
Material from Dr. Snyder's lecture notes for CS 211
Example - constructors
// in Person class:
public Person (String name, int age){
this.name = name;
this.age = age;
}

// in Student class:
public Student (int id, String name, int age){
super(name,age); // call parent constr
this.studentID = id;
} Material from Dr. Snyder's lecture notes for CS 211
Constructor Notes
Constructors are never inherited:
child class needs its own constructor.
child constructor MUST call parent constructor
first thing.
feed it the arguments it expects
Java tries to help by adding super() if you
don't call super(), but that requires the parent
class to have a no-params constructor.

Material from Dr. Snyder's lecture notes for CS 211


Constructors
This ensures the parent class still has total control
over all objects that may be treated as that type of
value:

child objects can't mess with anything without


parent class's permission (public/private/protected)

child classes can't even make objects without


parent's permission (every child object starts as a
parent-class object that gets specialized)

Material from Dr. Snyder's lecture notes for CS 211


The super Reference
Constructors aren't inherited, even when public

A child's constructor must call the parent's


constructor before anything else.

The super reference can also access other


variables/methods from parent.

try using super. Practice with empty


constructors first if needed.
Material from Dr. Snyder's lecture notes for CS 211
INHERITANCE AND
VISIBILITY

Material from Dr. Snyder's lecture notes for CS 211


What can a child class see?
If a parent class declares a field/method as:
public anyone can see these, so children can too.
private not even children get to see these
variables/methods. (They are still inherited, though)
protected children can also see, though nobody else
outside of the package can.
<default> anyone in the package can see;
if a child happens to be in the same package then yes,
but this locality is not always the case!

Material from Dr. Snyder's lecture notes for CS 211


Multiple Inheritance

Java only supports single inheritance, meaning that a


derived class can have only one parent class

Multiple inheritance allows a class to be derived from


two or more classes, inheriting the members of all
parents (other languages did this)

name collisions (between both parents) have to be


resolved.

Material from Dr. Snyder's lecture notes for CS 211


Overriding Methods
A child class can override the definition of an
inherited method in favor of its own

The child's method must have the same signature


as the parent's method, but can have a different
body

The type of the object executing the method


determines which version of the method is
invoked
child runs its version, parent runs its version.
Material from Dr. Snyder's lecture notes for CS 211
Overriding Methods

This is one place where you can tailor the functionality


of the child class to the particular type
Example
Base class Animal has a method makeNoise()
Child class Dog implements makeNoise() to print
woof!
grandchild class ScottishTerrier then might print
"woof at ye, scunner!"
Note that we must still have the same signature for
makeNoise()

Material from Dr. Snyder's lecture notes for CS 211


Overriding
A method in the parent class can be invoked
explicitly using the super reference

If a method is declared with the final


modifier, it cannot be overridden

The concept of overriding can be applied to data


called shadowing variables. And it's usually a bug.
Shadowing variables should be avoided because it tends
to cause unnecessarily confusing code
Material from Dr. Snyder's lecture notes for CS 211
Overloading vs. Overriding
Overloading deals with multiple methods with the
same name in the same class (perhaps inherited), but
with different signatures
Overriding deals with two methods, one in a parent
class and one in a child class, that have the same
signature. Child replaced what it inherited

Overloading lets you define a similar operation in


different ways for different parameters
Overriding lets you define the same operation in a
different way for the child class
Material from Dr. Snyder's lecture notes for CS 211
Class Hierarchies
A child class of one parent can be the parent of
another child, forming a class hierarchy
Business

RetailBusiness ServiceBusiness

KMart Macys Kinkos

Material from Dr. Snyder's lecture notes for CS 211


Class Hierarchies
Two children of the same parent are siblings
push common features as high in the class
hierarchy as you reasonably can (most reuse)

members are re-inherited every generation


child class inherits from all its ancestor classes

no single class hierarchy is appropriate for all


situations
Material from Dr. Snyder's lecture notes for CS 211
The Object Class
A class, Object, is defined in
java.lang

All classes derive from the Object class


If no parent class specified, Object used.

Therefore, the Object class is the


ultimate root of all class hierarchies
Material from Dr. Snyder's lecture notes for CS 211
The Object Class
Some methods inherited from Object:
String toString ()
we override this inherited method quite often.
inheritance is why that Classname@add12345
version of printing is always available to objects.

boolean equals(Object other)


Object's version uses == (memory location)
override to clarify for our class.
specialize: boolean equals (Person other)

Material from Dr. Snyder's lecture notes for CS 211


Abstract Classes
An abstract class is a placeholder in a class hierarchy
that represents a generic concept
An abstract class cannot be instantiated
abstract classes can be extended.

We use the modifier abstract on the class header


to declare a class as abstract:

public abstract class Product


{
// contents
}
Material from Dr. Snyder's lecture notes for CS 211
Abstract Classes
abstract classes may contain zero or more
abstract methods
abstract methods have no body: replace {} with ;

abstract modifier applied to each abstract method


non-abstract ('concrete') methods also allowed in an
abstract class. They will have bodies.
abstract class always marked abstract, then *might*
include abstract methods.
having an abstract method means the class must be
abstract.
Material from Dr. Snyder's lecture notes for CS 211
Abstract Classes
abstract class's child must override the abstract
methods of the parent, or it too will be abstract
An abstract method cannot be defined as final or
static.

The use of abstract classes is an important element of


software design it allows us to establish common
elements in a hierarchy that are too generic to
instantiate

Material from Dr. Snyder's lecture notes for CS 211


Abstract class example
abstract class Item represents buyable items
All items have a barcode (and associated
barcodeToString() method)
But Items are otherwise very different:
have an abstract method that generates HTML for
the item
Some items have images, some are related to others, etc.
The actual implementation of these abstract methods will be
specific to each item

Material from Dr. Snyder's lecture notes for CS 211


abstract: like a contract
When a class is abstract, the contract of "make an object for
me and I'll provide these methods/variables for you" is
unfulfilled, so we can't make objects of the abstract class.

A child class must fulfill that "contract" by overriding all the


abstract methods.
now all methods are available, and we can instantiate the
child class

sometimes a child class is also abstract; doesn't have to fulfill


the contract. (Leaves it to later generations)

Material from Dr. Snyder's lecture notes for CS 211


Visibility Revisited
It's important to understand one subtle issue related to
inheritance and visibility.

All variables and methods of a parent class, even


private members, are inherited by children

As we've mentioned, private members cannot be


referenced by name in the child class

However, private members inherited by child classes


exist and can be referenced/modified indirectly (e.g.,
through getters/setters)

Material from Dr. Snyder's lecture notes for CS 211


Visibility Revisited

Because the parent can refer to the private member,


the child can reference it indirectly using its parent's
methods

try gaining access to a parent's private variable from


a child class (using public/protected methods)

Material from Dr. Snyder's lecture notes for CS 211


Inheritance Design Issues

Every derivation should be an is-a relationship


a Student is-a Person; a Penguin is-a Bird.
Think about the potential future of a class hierarchy,
and design classes to be reusable and flexible
Find common characteristics of classes and push them
as high in the class hierarchy as appropriate
Override methods as needed to tailor functionality of
a child
Add new variables to children, but don't redefine
(shadow) inherited variables!

Material from Dr. Snyder's lecture notes for CS 211


Inheritance Design Issues
Allow each class to manage its own data; use the
super reference to invoke the parent's constructor to
set up its portion of the object's data
Even if there are no current uses for them, override
general methods such as toString and equals with
appropriate definitions
Use abstract classes to represent general concepts that
lower classes have in common
Use visibility modifiers carefully to provide needed
access without violating encapsulation

Material from Dr. Snyder's lecture notes for CS 211


Restricting Inheritance

final class: prohibits extending it


Thus, an abstract class cannot be declared as final it
would be useless!

final method: can't be overridden by children

These are key design decisions, establishing that


a method or class should be used as-is, and no
variation in implementation is possible.

Material from Dr. Snyder's lecture notes for CS 211


Abstract classes vs interfaces
You cannot instantiate an abstract class
Meant to "be implemented later"
But allows you to provide some non-abstract methods
with implementations, tie classes together

We'll learn about interfaces soon. Roughly, an interface


is a collection of abstract methods that can be
'implemented' (like inheriting). A class can only have
one parent, but can implement many interfaces.

When to use which and why?


Material from Dr. Snyder's lecture notes for CS 211
Interface Hierarchies

interfaces can inherit from each other


child interface inherits all abstract methods of the
parent, adds its own

A class implementing the child interface must define all


methods from both the ancestor and child interfaces

Note that class hierarchies and interface hierarchies


are separate (they do not extend each other ever)

Material from Dr. Snyder's lecture notes for CS 211

Das könnte Ihnen auch gefallen