Inheritance - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

Inheritance

Description:

A class can extend its inherited characteristics by adding instance variables ... In a well-designed class hierarch, polymorphism is employed as much as possible. ... – PowerPoint PPT presentation

Number of Views:105
Avg rating:3.0/5.0
Slides: 27
Provided by: wendyfree
Category:

less

Transcript and Presenter's Notes

Title: Inheritance


1
Inheritance
  • Java organizes classes in a hierarchy. Classes
    inherit the instance variables and methods of the
    classes above them in the hierarchy. A class can
    extend its inherited characteristics by adding
    instance variables and methods and by overriding
    inherited
  • methods. Thus inheritance provides a mechanism
    for reusing code and can greatly reduce the
    effort required to implement a new class.

2
Abstract Classes
  • Some classes in a hierarchy must never be
    instantiated. They are called abstract classes.
    Their sole purpose is to define features and
    behavior common to their subclasses.

3
Polymorphism
  • Methods in different classes with a similar
    function are usually given the same name. This
    is called polymorphism. Polymorphism makes
    classes easier to use because programmers need to
    memorize fewer methods names. In a well-designed
    class hierarch, polymorphism is employed as much
    as possible. A good example of a polymorphic
    message is toString. Every object no matter
    which class it belongs to understands the
    toString message and responds by returning a
    string that describes the object.

4
Pre and Post conditions
  • Clients need to know how to use a method
    correctly and what results to expect if it is so
    used. Preconditions specify the correct use of
    a method and post conditions describe what will
    result if the preconditions are satisfied.

5
Exceptions for error handling
  • When a methods preconditions are violated, a
    foolproof way to catch the errors is to throw
    exceptions, thereby halting program execution at
    the point of the errors.

6
Reference Types
  • The identity of an object and the fact that there
    can be multiple references to the same object are
    issues that arise when comparing two objects for
    equality and when copying an object. There are
    also subtle rules to master when manipulating
    objects of different but related types in a
    hierarchy.

7
  • Class variablebelongs to a class
  • Class method is activated when a message is sent
    to the class rather than to an object.
  • Static is used to designate class variables and
    methods.

8
Example static variable and method
  • public class Student
  • private String name
  • int test new int3
  • public Student()
  • studentCount
  • name" "
  • for(int x0xlttest.lengthx)
  • testx0
  • public void setName(String n)
  • namen
  • static private int studentCount

9
Rules for Using Static variables
  • Class methods can reference only the static
    variables, and never the instance variables.
  • Instance methods can reference static and
    instance variables.

10
  • import java.util.Scanner
  • public class Convert
  • private static Scanner scanner new
    Scanner(System.in)
  • public static void main(String args)
  • while(true)
  • printCelsius(convertToCelsius(readFah
    renheit()))
  • private static double readFahrenheit()
  • System.out.println("Enter degrees
    Fahrenheit ")
  • double xscanner.nextInt()
  • return x
  • private static double convertToCelsius(dou
    ble fahrenheit)

11
Why not use static all the time?
  • Makes for awkward and difficult to maintain
    programs. Rather than break up into static
    methods etc, break tasks up into a system of
    cooperating classes.

12
Exercises
  • 1. Describe the manner in which Java allocates
    memory for instance variables and static
    variables.
  • 2. List three possible situations in which
    static methods might me included in classes
  • 3. what error occurs in the following code?

public class SomeClass private int
instVar0 static public void someMethod(int
x) classVar instVar classVar
x static private int classVar0
13
  • Exercise 9.1
  • Java allocates a separate set of memory cells in
    each instance for the instance variables of a
    class. By contrast, only one set of cells is
    allocated for the class variables.
  • First, a static method can be included to allow
    the user to call the method by sending a message
    to the class. This method can serve as a public
    accessor or mutator of a class variable. Second,
    a static method can be included to perform some
    useful calculation. The Math class methods are
    good examples. Third, a static method can be
    included in a set of cooperating helper methods
    to decompose responsibilities for tasks in a
    class.
  • The reference to instVar in the static method is
    a syntax error because static methods cannot
    reference instance variables.
  • A public constant is accessible to all clients,
    and a static constant is accessible by using the
    class name as a reference.

14
What is an interface?
  • 1. State the purpose of a Java interface.
  • 2. Why dont all classes have interfaces?

15
  • A Java interface specifies the set of public
    methods for classes that implement that
    interface. It serves as a form of glue that
    holds the parts of a software system together.
  • Some classes are so simple that they do not need
    interfaces moreover, an interface is commonly
    used when there is more than one implementing
    class.

16
  • An interface contains only methods, never
    variables.
  • The methods in a n interface are usually public
  • If more than one class implements an interface,
    its methods are polymorphic
  • A class can implement methods in addition to
    those listed in the interface, as we will
    illustrate soon.
  • A class can implement more than one interface, a
    feature that we are not going to explore
  • Interfaces can be organized in an inheritance
    hierarchy, another feature we are not going to
    explore.

17
Exercises
  • Write an interface for Student
  • When the programmer uses the expression
    implements ltan interfacegtin a class definition,
    how does the compiler react?

18
  • public interface StudentSpecs
  • public void setName (String nm)
  • public String getName ()
  • public void setScore (int i, int score)
  • public int getScore (int i)
  • public int getAverage()
  • public int getHighScore()
  • public String toString()
  • The expression implements ltan interfacegt causes
    the compiler to check the implementing class for
    the presence of all the methods in the specified
    interface. If any of them are missing, a syntax
    error occurs.

19
Exercises
  • 1. What is class hierarchy? Give an example
  • 2. What syntax is used to get one class to
    inherit data and behavior form another class?
  • 3. How does the keyword super work with
    constructors?
  • How does the keyword super work with methods
    other than constructors?
  • What is the role of the visibility modifier
    protected in a class hierarchy?
  • Find the error in the following code and suggest
    a remedy for the problem
  • Shape s new Wheel()
  • S.setSpokes(5)

20
  • A class hierarchy is a set of classes that is
    organized by the relationship of subclass and
    superclass. An example is the hierarchy
    Object/Circle/Wheel, where Circle is a subclass
    of Object and Wheel is a subclass of Circle.
  • The expression extends lta classgt is used to
    inherit the data and behavior of another class.
  • To run a constructor of the same form in the
    superclass, one uses the form super(ltparametersgt)
    at the beginning of the corresponding constructor
    in the subclass.
  • With methods other than constructors, one uses
    the form super.ltmethod namegt (ltparametersgt).
  • The visibility modifier protected allows
    subclasses in a hierarchy to access instance and
    class variables or methods of superclasses
    without allowing other clients in the system to
    access these items.
  • There is a syntax error. The method setSpokes is
    not included in the Shape interface. The
    programmer attempts to send this message to an
    instance of Wheel, but this object is
    masquerading as a Shape. The variable s must be
    cast to a Wheel before sending it the setSpokes
    message.

21
Exercises contd
  • 1. What is an abstract class? Give an example.
  • Why do we declare abstract methods?
  • What is a final method? Give an example.

22
  • An abstract class serves as a repository of data
    and behavior common to a set of subclasses.
    Because this class is abstract, it cannot be
    instantiated. An example is the AbstractShape
    class, which is abstract and defines the behavior
    common to circles and rectangles.
  • We declare abstract methods for two possible
    reasons. First, the abstract class in which they
    are declared implements an interface, but the
    implementation of these methods is deferred to
    the concrete classes. Second, even if there is
    no interface, these methods must be implemented
    in all subclasses, so declaring them abstract
    enforces this.
  • A final method cannot be overridden in a
    subclass. Examples are the accessors for
    variables that are defined in an abstract class.
    These methods should not be overridden by
    subclasses.

23
Observations
  • A java interface has a name and consists of a
    list of method headers.
  • One or more classes can implement the same
    interface.
  • If a variable is declared to be of an interface
    type, then it can be associated with an object
    form any class that implements the interface.
  • If a class implements an interface, then all its
    subclasses do so implicitly.
  • A subclass inherits all the characteristics of
    its superclass. To this basis the subclass can
    add new variables and methods or modify inherited
    methods.
  • Characteristics common to several classes can be
    collected in a common abstract surperclass that
    is never instantiated
  • An abstract class can contain headers for
    abstract methods that are implemented in the
    subclass.
  • A classs constructors and methods can utilize
    constructors and methods that are implemented in
    the subclasses.
  • A classs constructors and methods can utilize
    constructors and methods in the superclass
  • Inheritance reduces repetition and promotes the
    reuse of code.
  • Interfaces and inheritance promote the use of
    polymorphism.

24
How does it work?
  • When a message is sent to an object, Java looks
    for a matching method. The search starts in the
    objects class and if necessary continues up the
    class hierarchy.

25
  • Do fill in the blank on page 312
  • Do project 9-1 and 9-5

26
  • 1. Methods and variables that belong to a class
    rather than an instance are called class or
    static variables and methods.
  • 2. The keyword used to invoke a constructor or
    method in a superclass is called super.
  • 3. The visibility modifier protected makes a
    method or variable visible to subclasses but not
    to other clients.
  • 4. A(n) abstract class contains common behavior
    and data for a set of subclasses but is not
    instantiated.
  • 5. A(n) abstract method consists of just a head
    and forces all subclasses to implement it.
  • 6. Preconditions and postconditions state the
    assumptions that are true before a method
    executes correctly and after it executes
    correctly.
  • 7. The method equals is the conventional Java
    method for comparing two objects for equality,
    whereas the method clone is the conventional Java
    method for copying an object.
Write a Comment
User Comments (0)
About PowerShow.com