Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction To Scientific Programming Chapter 7 – Inheritance or (More on Classes)

Similar presentations


Presentation on theme: "Introduction To Scientific Programming Chapter 7 – Inheritance or (More on Classes)"— Presentation transcript:

1 Introduction To Scientific Programming Chapter 7 – Inheritance or (More on Classes)

2 S.Horton/107/Ch. 7Slide 2 Lecture Overview On Inheritance I.Inheritance Basics I.Class Hierarchy II.Derived Classes III.Overriding II.Programming With Inheritance I.Methods II.Variables III.Constructors IV.Assignments III.Abstract Classes (skipping interfaces) IV.Dynamic Binding & Polymorphism

3 S.Horton/107/Ch. 7Slide 3 I. Inheritance Basics Inheritance allows you to define a “generic” class and then later define more specialized classes that add new detail relative to the generic class. This “generic” class is called the base or parent class. Specialized classes are derived from the base class and are called derived or child classes The specialized classes inherit all the properties of the base class. After the general class is developed you only have to write the difference or specialization code for each derived class.

4 S.Horton/107/Ch. 7Slide 4 Class Hierarchy With a base class and any derived class(es), a structure or hierarchy is established. Any class lower in the hierarchy is a descendent class. Any class higher in the hierarchy is an ancestor class. This hierarchy can have as many levels as required. That is, a class can be derived from derived classes (child classes can be parent classes!). Note: this class hierarchy exists for all classes including all built-in Java classes/packages.

5 S.Horton/107/Ch. 7Slide 5 What Does Inheritance Do For Me? Inheritance helps accomplish several of the main goals of object oriented programming (OOP): Reduce the complexity of programs by only requiring “specialized” code for many tasks; Simplify the tasks of writing, testing, and maintaining complex programs by breaking down the problem into sub-parts; Promotes the reuse of classes developed for one application to another application (instead of writing new programs from scratch).

6 S.Horton/107/Ch. 7Slide 6 Example Of A Class Hierarchy The base or generic class can be used to implement specialized classes (e.g. student, employee, faculty, …) Classes can be derived from the classes derived from the base class. Person StudentEmployee FacultyStaffUndergraduateGraduate MastersDegreeNonDegreePhD

7 S.Horton/107/Ch. 7Slide 7 "Is a" and "Has a" Relationships Inheritance is useful for "is a" relationships. A student "is a" person. Student inherits from Person. Inheritance is usually not useful for "has a" relationships. A student "has a(n)" enrollment date. Just add a Date instance variable to Student instead of having Student inherit from a class called Date.

8 S.Horton/107/Ch. 7Slide 8 Example Of Inheritance: a Person Base Class public class Person { private String name; //Default constructor public Person() { name = "No name yet."; } //Constructor to init Person name public Person(String initialName) { name = initialName; } //Mutator to set Person name public void setName(String newName) { name = newName; } //Accessor to get Person name public String getName() { return name; } … … //Method to output Person name public void writeOutput() { System.out.println("Name: " + name); } //Method to check if same name public boolean sameName(Person otherPerson) { return (this.name.equalsIgnoreCase( otherPerson.getName())); }

9 S.Horton/107/Ch. 7Slide 9 Notes On Person Base Class Constructors: A default constructor One that initializes the name attribute (instance variable) Accessor methods: setName to change the value of the name attribute getName to read the value of the name attribute writeOutput to display the value of the name attribute One other class method: sameName to compare the values of the name attributes for objects of the class.

10 S.Horton/107/Ch. 7Slide 10 Notes On Person Base Class - II The name attribute is private This encapsulates the data. It keeps the data local to the base class and prevents descendant classes from corrupting it. Data values are still accessible through methods. The methods in Person are public This is necessary so that child classes can access (take advantage of) base class methods and data.

11 S.Horton/107/Ch. 7Slide 11 To create a derived class, use the extends reserved word: The keyword extends in first line indicates inheritance. E.g. - derived class Student from base class Person A derived class has the instance variables and methods of the base class that it extends. The Person class has a name instance variable so the Student class will also have a name instance variable. Can call the setName method with a Student object even though setName is defined in Person and not in Student : Derived Classes public class Student extends Person Student s = new Student(); s.setName(“Jeff Davis");

12 S.Horton/107/Ch. 7Slide 12 Extending A Class A derived class can add instance variables and/or methods to those it inherits from its base class. Think of a derived class as having access to itself and all of its ancestors. Example: consider the derived class Student from base class Person (Display 7.3 on p. 419 of Savitch - Third Edition) An instance variable has been added to Student Student has studentNumber in addition to name, which it inherited from Person Student also has several additional methods: reset, getStudentNumber, setStudentNumber, writeOutput, equals, and some constructors

13 S.Horton/107/Ch. 7Slide 13 Example Of A Class Hierarchy - Revisited Each descendant (derived) class has potential access to all ancestor classes. A “superclass” is all ancestor classes for a derived class. Person StudentEmployee FacultyStaffUndergraduateGraduate MastersDegreeNonDegreePhD

14 S.Horton/107/Ch. 7Slide 14 Overriding Methods When a child class has a method with the same signature as the parent class, the method in the child class overrides the one in the parent class! This is overriding, not overloading. Example: Both Person and Student have a writeOutput method with no parameters (same signature). When writeOutput is called with a Student object, the writeOutput in Student will be used, not the one in Person.

15 S.Horton/107/Ch. 7Slide 15 Overriding vs. Overloading Overloading Same method name Different signatures Both methods can be in same class Overriding Same method name Same signature One method in ancestor, one in descendant of ancestor

16 S.Horton/107/Ch. 7Slide 16 The final Modifier This specifies that a method definition cannot be overridden with a new definition in a derived class Example: public final void specialMethod() Used in specification of some methods and constants in standard libraries Constants such as pi, e in Math class Certain system and user interface methods (forms, dialogs,…) You can also declare an entire class to be final, which means it cannot be used as a base class to derive another class.

17 S.Horton/107/Ch. 7Slide 17 Recall, access to any public method for any derived class object (or any of it’s ancestors), is available by invoking the method name: You can call the setName method with a Student object even though setName is defined in Person and not in Student : This is possible because setName is a public method. private methods are not available outside of the class nor by any descendant class (only in the class in which it is defined). This means private methods are not inherited. II. Programming With Inheritance - Methods Student s = new Student(); s.setName(“Jeff Davis");

18 S.Horton/107/Ch. 7Slide 18 What About Overridden Methods? Internally, you can still access overridden methods in descendant classes! In fact, many times it is preferred. External to the class, an overridden method means that only the descendant method is invoked when the descendant object is used. But internally, this descendant method can invoke the method it overrode in the ancestor class!

19 S.Horton/107/Ch. 7Slide 19 Overridden Methods - II Use super to call a method in the parent class that was overridden (redefined) in the derived class Example: Student redefined the method writeOutput of its parent class, Person Can use super.writeOutput() to invoke the overridden (parent) method public void writeOutput() { super.writeOutput(); System.out.println("Student Number :“ + studentNumber); }

20 S.Horton/107/Ch. 7Slide 20 Instance Variables public instance variables from ancestor classes are available by name in derived classes. private instance variables from ancestor classes are not available by name in derived classes One should use accessor methods to change them. E.g. a reset method for a Student object to change the name attribute Can you have a public instance variable with the same name in derived classes?

21 S.Horton/107/Ch. 7Slide 21 A Constructor In A Derived Class A constructor initializes a class object, so in any derived class, how do you initialize all of the ancestors which the class might reference? You need to invoke the ancestors’ constructors (i.e. constructors that can call other constructors) This is accomplished by using the reserved word super to invoke a constructor in parent class super should be first action in a constructor definition It is included automatically by Java if it is not there super() calls the parent default constructor

22 S.Horton/107/Ch. 7Slide 22 Example of A Constructor in a Derived Class Student The Student constructor first calls super() which calls a constructor in Person (which initializes the private instance variable name ). Then, it initializes private instance variable studentNumber to 0. public class Student extends Person { private int studentNumber; //Default constructor public Student() { super(); studentNumber = 0; } …

23 S.Horton/107/Ch. 7Slide 23 Example of An Overloaded Constructor In Derived Class Student  This passes the parameter newName to a different constructor in the parent class.  Then, it takes the second parameter to initialize the local private instance variable. public class Student extends Person { … public Student(String newName, int newStudentNumber) { super(newName); studentNumber = newStudentNumber; } …

24 S.Horton/107/Ch. 7Slide 24 Another Option – Referencing Constructors Within A Class this used in a constructor references another constructor within the class. public class Student extends Person { … //Constructor option #2 public Student(String newName, int newStudentNumber) { super(newName); studentNumber = newStudentNumber; } //Constructor option #3 public Student(String initialName) { this(initialName, 0); } …

25 S.Horton/107/Ch. 7Slide 25 Another “Feature” Of OOP Languages w/ Inheritance Derived classes have more than one type! They have the type of the class they define – the derived class. They also have the type of every ancestor class (all the way to the root).

26 S.Horton/107/Ch. 7Slide 26 Inheritance Specifics For Java All classes derive from an original, predefined class called Object Object is called the Eve class since it is the original class for all other classes. This means that all objects have more than one type – their own and Object !

27 S.Horton/107/Ch. 7Slide 27 … Person president = new Person(“Steve Horton”); Employee human = new Employee(“Steve Horton”); if (human.sameName(president)) { //Does this block execute? System.out.println(“Your employee is the president.”); } … Derived Class Type Example Check the type definition in the employee class for method sameName. This code works because the derived class Employee has the type of both Employee and Person. Note: the compiler checks all possible types when resolving references – this is called type checking (it is involved!). Does this generate a compiler error?

28 S.Horton/107/Ch. 7Slide 28 Further Detail On Assignment Compatibility Not allowed OK Person Employee Person is the parent class of Employee in this example. You can assign an object of a derived class to a variable of any ancestor type Person josephine; Employee boss = new Employee(); josephine = boss; You cannot assign an object of an ancestor class to a variable of a derived class type Person josephine = new Person(); Employee boss; boss = josephine;

29 S.Horton/107/Ch. 7Slide 29 III. Abstract Classes An abstract class is used as a base for inheritance instead of being used to create objects (you actually cannot create objects of an abstract class). Abstract classes bring structure to program design by requiring you to supply methods that would otherwise always be overridden. Specify that a method is abstract if you want all descendant classes to implement it: public abstract void drawHere(); Note: any class that has an abstract method must be declared as an abstract class: public abstract class Figure

30 S.Horton/107/Ch. 7Slide 30 Abstract Class Example Examine the class Figure in Savitch, Third Edition p.455 as part of the character graphics program. Figure is an abstraction so no direct implementation. It serves as a base class for other descendant classes. It could be defined as an abstract class. The method drawHere should be overridden in all descendant classes derived from Figure based on the specifics of each descendant class. Hence, drawHere could be defined as abstract in Figure.

31 S.Horton/107/Ch. 7Slide 31 Savitch Character Graphics Inheritance Structure Figure BoxTriangle Instance variables: offset Methods: setOffsetgetOffset drawAtdrawHere Instance variables: offsetheightwidth Methods: setOffsetgetOffset drawAtdrawHere resetdrawHorizontalLine drawSidesdrawOneLineOfSides spaces Instance variables: offsetbase Methods: setOffsetgetOffset drawAtdrawHere resetdrawBase drawTopspaces Inherited Overrides Static

32 S.Horton/107/Ch. 7Slide 32 Many times a program needs to execute in a non- sequential order. Examples include: Selection (if-else/switch) Repetition (while/do-while/for) Method calls Program must jump to memory location that contains the method's instructions and return to the calling program when the method is finished. This branching requires that the complier compute the address of the memory location to branch to. The compiler cannot always know the address! Sometimes, an address can only be determined at run time. IV. Introduction to “Dynamic Binding”

33 S.Horton/107/Ch. 7Slide 33 Example Of Why Dynamic Binding Happens With inheritance, a derived class can call a method in their parent class. Since objects from the two classes can be created at separate times, the compiler cannot possibly know which address to use Therefore, the address of the ancestor method must be determined (bound) at run time.

34 S.Horton/107/Ch. 7Slide 34 Definitions: Static And Dynamic Binding Static binding is the process of determining branching addresses at compile time. Dynamic binding is the process of determining branching addresses at runtime (or during program execution). Binding done at runtime is also called late binding.

35 S.Horton/107/Ch. 7Slide 35 Dynamic Binding Enables Polymorphism Polymorphism means “having many forms” Using the process of dynamic binding to allow different objects to use the same method name but perform different method actions is polymorphism Hence, polymorphism allows us to apply a consistent approach to inconsistent but related behaviors There is no specific syntax for polymorphism, it is how you design it – a combination of inheritance and overloading.

36 S.Horton/107/Ch. 7Slide 36 Examples Of Polymorphism Sorting data with different data types: objects, arrays, primitives, … Drawing programs that display various types of shapes with different implementations of.draw Use of System.out.println with different implementations of.toString

37 S.Horton/107/Ch. 7Slide 37 For Lab - Class Hierarchy For Geometric Shapes Does this diagram satisfy “Is-a” relationships? What are the common elements to all shapes? What other data is needed for each class? Shape Rectangle Triangle Right Triangle Circle Isosceles Triangle


Download ppt "Introduction To Scientific Programming Chapter 7 – Inheritance or (More on Classes)"

Similar presentations


Ads by Google