1 / 37

Introduction To Scientific Programming

Introduction To Scientific Programming. Chapter 7 – Inheritance or (More on Classes). Lecture Overview On Inheritance. Inheritance Basics Class Hierarchy Derived Classes Overriding Programming With Inheritance Methods Variables Constructors Assignments

lgrounds
Télécharger la présentation

Introduction To Scientific Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Lecture Overview On Inheritance • Inheritance Basics • Class Hierarchy • Derived Classes • Overriding • Programming With Inheritance • Methods • Variables • Constructors • Assignments • Abstract Classes (skipping interfaces) • Dynamic Binding & Polymorphism

  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. 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. 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. Person Student Employee Undergraduate Graduate Faculty Staff MastersDegree PhD NonDegree 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.

  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. Example Of Inheritance:a Person Base Class … //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())); } } 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; } …

  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. 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. Derived Classes • To create a derived class, use the extends reserved word: • The keyword extendsin 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: public class Student extends Person Student s = new Student(); s.setName(“Jeff Davis");

  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. Person Student Employee Undergraduate Graduate Faculty Staff MastersDegree PhD NonDegree 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.

  14. 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. Overriding Methods

  15. 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 Overriding vs. Overloading

  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. II. Programming With Inheritance - Methods • 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. Student s = new Student(); s.setName(“Jeff Davis");

  18. 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! What About Overridden Methods?

  19. 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 Overridden Methods - II public void writeOutput() { super.writeOutput(); System.out.println("Student Number :“ + studentNumber); }

  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. 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 superto invoke a constructor in parent class • supershould 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. Example of A Constructor in a Derived Class Student public class Student extends Person { private int studentNumber; //Default constructor public Student() { super(); studentNumber = 0; } … • 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.

  23. Example of An Overloaded Constructor In Derived Class Student public class Student extends Person { … public Student(String newName, int newStudentNumber) { super(newName); studentNumber = newStudentNumber; } … • 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.

  24. this used in a constructor references another constructor within the class. Another Option – Referencing Constructors Within A 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. 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. 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. Derived Class Type Example … 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.”); } … • 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. Person Employee Person is the parent class of Employee in this example. Further Detail On Assignment Compatibility • 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; OK Not allowed

  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. 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, drawHerecould be defined as abstract in Figure.

  31. Inherited Overrides Static Figure Box Triangle Savitch Character Graphics Inheritance Structure Instance variables: offset Methods: setOffset getOffset drawAt drawHere Instance variables: offset height width Methods: setOffset getOffset drawAtdrawHere reset drawHorizontalLine drawSides drawOneLineOfSides spaces Instance variables: offset base Methods: setOffset getOffset drawAtdrawHere reset drawBase drawTop spaces

  32. IV. Introduction to “Dynamic Binding” • 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.

  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. 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. 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. 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. For Lab - Class Hierarchy For Geometric Shapes Shape • Does this diagram satisfy “Is-a” relationships? • What are the common elements to all shapes? • What other data is needed for each class? Rectangle Circle Triangle Right Triangle Isosceles Triangle

More Related