Computer Science II - PowerPoint PPT Presentation

1 / 48
About This Presentation
Title:

Computer Science II

Description:

... single inheritance, meaning that a derived class can have only one parent class ... Thought parked = new Thought(); Advice dates = new Advice(); parked.message ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 49
Provided by: Zhiy2
Category:

less

Transcript and Presenter's Notes

Title: Computer Science II


1
Computer Science II
  • CS132/601
  • Lecture 3

2
Example on the Impact of a Superclass without
no-arg Constructor
Find out the errors in the program
public class Apple extends Fruit   class
Fruit public Fruit(String name)
System.out.println("Fruit's constructor is
invoked")
3
Declaring a Subclass
  • A subclass extends properties and methods from
    the superclass. You can also
  • Add new properties
  • Add new methods
  • Override the methods of the superclass

4
Multiple Inheritance
  • Java 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
  • Collisions, such as the same variable name in two
    parents, have to be resolved
  • Java does not support multiple inheritance
  • In most cases, the use of interfaces gives us
    aspects of multiple inheritance without the
    overhead

5
Multiple Inheritance
6
Overriding Methods
  • A child class can override the definition of an
    inherited method in favor of its own
  • The new 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

7
//
// Messages.java Java
Foundations // // Demonstrates the use of an
overridden method. //
public
class Messages //----------------------------
------------------------------------- //
Creates two objects and invokes the message
method in each. //-----------------------------
------------------------------------ public
static void main (String args)
Thought parked new Thought() Advice
dates new Advice() parked.message()
dates.message() // overridden
8
//
// Thought.java Java
Foundations // // Represents a stray thought.
Used as the parent of a derived // class to
demonstrate the use of an overridden
method. //
public class
Thought //-----------------------------------
------------------------------ // Prints a
message. //------------------------------------
----------------------------- public void
message() System.out.println ("I feel
like I'm diagonally parked in a "
"parallel universe.")
System.out.println()
9
//
// Advice.java Java
Foundations // // Represents some thoughtful
advice. Used to demonstrate the use // of an
overridden method. //
public
class Advice extends Thought
//------------------------------------------------
----------------- // Prints a message. This
method overrides the parent's version.
//------------------------------------------------
----------------- public void message()
System.out.println ("Warning Dates in
calendar are closer "
"than they appear.") System.out.println()
super.message() // explicitly invokes
the parent's version
10
Overriding
  • A method in the parent class can be invoked using
    super reference
  • a method with the final modifier cannot be
    overridden
  • overriding can be applied to data
  • is called shadowing variables

11
Overloading vs. Overriding
  • Overloading deals with multiple methods with
    different signatures
  • Overriding deals with two methods, one in a
    parent class and one in a child class, that have
    the same signature
  • Overloading lets you define a similar operation
    in different ways for different parameters
  • Overriding lets you define a similar operation in
    different ways for different object types

12
NOTE
An instance method can be overridden only if it
is accessible. A private method cannot be
overridden. If a method defined in a subclass is
private in its superclass, the two methods are
completely unrelated.
13
NOTE
A static method can be inherited. However, a
static method cannot be overridden. If a static
method defined in the superclass is redefined in
a subclass, the method defined in the superclass
is hidden.
14
Overriding vs. Overloading
15
Class Hierarchies
  • A child class of one parent can be the parent of
    another child, forming a class hierarchy

16
Class Hierarchies
  • Two children of the same parent are called
    siblings
  • Common features should be put as high in the
    hierarchy as is reasonable
  • An inherited member is passed continually down
    the line
  • Therefore, a child class inherits from all its
    ancestor classes
  • There is no single class hierarchy that is
    appropriate for all situations

17
An Alternate Class Hierarchy
18
The Object Class
  • A class called Object is defined in the java.lang
    package of the Java standard class library
  • All classes are derived from the Object class
  • If a class is not explicitly defined to be the
    child of an existing class, it is assumed to be
    the child of the Object class
  • Therefore, the Object class is the ultimate root
    of all class hierarchies

19
The Object Class
  • The Object class contains a few useful methods
  • For example, toString method
  • When defining the toString method, we are
    actually overriding an inherited definition
  • The toString method in the Object class is
    defined to return a string that contains the name
    of the objects class along with some other
    information
  • E.g. Faculty_at_1befab0

20
The Object Class
  • The equals method of the Object class returns
    true if two references are aliases
  • We can override equals to define equality in some
    more appropriate way
  • E.g. String class if two String objects contain
    the same characters

21
Abstract Classes
  • An abstract class is a placeholder in a class
    hierarchy that represents a generic concept
  • An abstract class cannot be instantiated

public abstract class Product // contents
22
Abstract Classes
  • An abstract class often contains abstract methods
    with no definitions
  • Also, an abstract class typically contains
    non-abstract methods with full definitions
  • A class declared as abstract does not have to
    contain abstract methods

23
Abstract Classes
  • The child of an abstract class must override the
    abstract methods of the parent, or it too will be
    considered 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

24
An Abstract Class in UML
Abstract classes and methods are shown in italics
font.
25
Interface Hierarchies
  • Inheritance can be applied to interfaces as well
    as classes
  • one interface can be derived from another
    interface
  • The child interface inherits all abstract methods
    of the parent
  • 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 distinct (they do not overlap)

26
Visibility Revisited
  • All variables and methods of a parent class, even
    private members, are inherited by its children
  • Private members cannot be referenced by name in
    the child class
  • However, private members inherited by child
    classes exist and can be referenced indirectly

27
Visibility Revisited
  • Because the parent can refer to the private
    member, the child can reference it indirectly
    using its parent's methods
  • The super reference can be used to refer to the
    parent class, even if no object of the parent
    exists

28
//
// FoodItem.java Java
Foundations // // Represents an item of food.
Used as the parent of a derived class // to
demonstrate indirect referencing. //

public class FoodItem final private
int CALORIES_PER_GRAM 9 private int
fatGrams protected int servings
//------------------------------------------------
----------------- // Sets up this food item
with the specified number of fat grams // and
number of servings. //-------------------------
----------------------------------------
public FoodItem (int numFatGrams, int
numServings) fatGrams numFatGrams
servings numServings (more)
29
//---------------------------------------------
-------------------- // Computes and returns
the number of calories in this food item //
due to fat. //---------------------------------
-------------------------------- private int
calories() return fatGrams
CALORIES_PER_GRAM //--------------------
---------------------------------------------
// Computes and returns the number of fat
calories per serving. //-----------------------
------------------------------------------
public int caloriesPerServing() return
(calories() / servings)
30
//
// Pizza.java Java
Foundations // // Represents a pizza, which is a
food item. Used to demonstrate // indirect
referencing through inheritance. //

public class Pizza extends FoodItem
//------------------------------------------------
----------------- // Sets up a pizza with the
specified amount of fat (assumes // eight
servings). //----------------------------------
------------------------------- public Pizza
(int fatGrams) super (fatGrams, 8)

31
//
// FoodAnalyzer.java
Java Foundations // // Demonstrates indirect
access to inherited private members. //

public class FoodAnalyzer
//------------------------------------------------
----------------- // Instantiates a Pizza
object and prints its calories per //
serving. //------------------------------------
----------------------------- public static
void main (String args) Pizza
special new Pizza (275)
System.out.println ("Calories per serving "
special.caloriesPerServing(
))
32
Designing for Inheritance
  • As we've discussed, taking the time to create a
    good software design reaps long-term benefits
  • Inheritance issues are an important part of an
    object-oriented design
  • Properly designed inheritance relationships can
    contribute greatly to the elegance,
    maintainability, and reuse of the software

33
Inheritance Design Issues
  • Every derivation should be an is-a relationship
  • 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 appropriate to tailor or
    change the functionality of a child
  • Add new variables to children, but don't redefine
    (shadow) inherited variables

34
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 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

35
Restricting Inheritance
  • The final modifier can be used to curtail
    inheritance
  • If the final modifier is applied to a method,
    then that method cannot be overridden in any
    descendent classes
  • If the final modifier is applied to an entire
    class, then that class cannot be used to derive
    any children at all
  • Thus, an abstract class cannot be declared as
    final

36
Summary
  • Chapter 8 focused on
  • deriving new classes from existing classes
  • the protected modifier
  • creating class hierarchies
  • abstract classes
  • indirect visibility of inherited members
  • designing for inheritance

37
Programs
38
Ch. 8 Review
  • 1. The process of inheritance should establish
    a(n) ___________________ relationship.
  • a) is-a
  • b) has-a
  • c) static
  • d) not-a
  • e) none of the above
  • Answer a
  • Explanation Inheritance should establish an
    is-a relationship. Therefore any objects that
    are of a type lower in the inheritance hierarchy
    are also of a type higher in the inheritance
    hierarchy.

39
  • 2. The special reference _________________ is
    used to refer to the parent class in a child
    class.
  • a) this
  • b) super
  • c) null
  • d) parent
  • e) none of the above
  • Answer b
  • Explanation The super reference refers to the
    parent class in a derived class.

40
  • 3. Which of the following key words indicates a
    new class is being derived from an existing
    class?
  • a) super
  • b) final
  • c) extends
  • d) inherits
  • e) expands
  • Answer c
  • Explanation The key word extends indicates
    that a new class is being derived from an
    existing class.

41
  • 4. When designing a class hierarchy, it is
    important that common features be
    ________________________ .
  • a) higher in the class hierarchy.
  • b) lower in the class hierarchy.
  • c) near the middle of the class hierarchy.
  • d) in abstract classes.
  • e) in the Object class.
  • Answer a
  • Explanation Common features should be included
    closer to the top of the class hierarchy. Doing
    this makes them available to more classes lower
    in the hierarchy.

42
  • 5. Methods and variables declared as private in a
    parent class cannot be accessed in a child class.
  • Answer True
  • Explanation In order for a child class to have
    access to the private data and methods of a
    parent class, they should be declared using the
    protected modifier, which still enforces
    encapsulation, but allows for flexibility in an
    inheritance hierarchy.

43
  • 6. A child class is allowed to define a method
    with the same name and parameter list as a method
    in the parent class.
  • Answer True
  • Explanation A subclass is allowed to override
    methods that are in the parent class.

44
  • 7. It is possible to derive a class from an
    abstract class without overriding all of the
    parents abstract methods.
  • Answer True
  • Explanation The child class must also be
    declared as abstract in this case.

45
  • 8. Explain why inheritance is useful.
  • Answer Inheritance is useful because it allows
    for code-reuse. This means that if we have
    multiple software entities that have common
    features, the code for the common features can be
    written once in a superclass. The classes that
    include these features can then be written via
    inheritance, and this common code does not have
    to be rewritten.

46
  • 9. Explain the relevance of the Object class to
    the Java programming language.
  • Answer Every class in Java is a subclass of the
    Object class. This occurs whether a class
    definition explicitly extends the Object class or
    not. Therefore, every class in Java has a common
    set of methods that are defined in the Object
    class. These include the toString method and the
    equals method.

47
  • 10. Draw a hierarchy of Animals. The hierarchy
    should include the following entities Animal,
    Reptile, Mammal, Bear, Human, Iguana, and
    Dolphin.
  • Answer
  • Animal
  • / \
  • Reptile Mammal
  • / / \
  • Iguana Bear Human Dolphin

48
  • Ch. 8 Lab
Write a Comment
User Comments (0)
About PowerShow.com