690 likes | 712 Views
Chapter 11 Inheritance and Polymorphism. Objectives. To define a subclass from a superclass through inheritance (§11.2). To invoke the superclass’s constructors and methods using the super keyword (§11.3). To override instance methods in the subclass (§11.4).
E N D
Objectives • To define a subclass from a superclass through inheritance (§11.2). • To invoke the superclass’s constructors and methods using the super keyword (§11.3). • To override instance methods in the subclass (§11.4). • To distinguish differences between overriding and overloading (§11.5). • To explore the toString() method in the Object class (§11.6). • To discover polymorphism and dynamic binding (§§11.7–11.8). • To describe casting and explain why explicit downcasting is necessary (§11.9). • To explore the equals method in the Object class (§11.10). • To store, retrieve, and manipulate objects in an ArrayList (§11.11). • To implement a Stack class using ArrayList (§11.12). • To enable data and methods in a superclass accessible from subclasses using the protected visibility modifier (§11.13). • To prevent class extending and method overriding using the final modifier (§11.14).
4 Fundamental Principles of OOP • 1. Inheritance • Inherit members from parent class • 2. Abstraction • Define and execute abstract actions • 3. Encapsulation • Hide the internals of a class • 4. Polymorphism • Access a class through its parent interface 3
Types of Inheritance • Inheritance terminology base class / parent class derived class inherits class interface implements derived interface implements base interface 5
Inheritance • Inheritance Objects can relate to each otherwith either a “has a, parent”, “uses, child of parent” or an “is a” relationship. “Is a, parent it self” is the inheritance way of object relationship. • Like., family tree. • This LibraryAsset is a superclass, or base class, that maintains only the data and methods that are common to all loanable assets. Book, magazine, audiocassette and microfilm will all be subclasses or derived classes or the LibraryAsset class, and so they inherit these characteristics. The inheritance relationship is called the “is a” relationship. A book “is a” LibraryAsset, as are the other 3 assets.
Public Class LibraryAsset Private _title As String Public Property Title() As String Get Return _title End Get Set(ByVal Value As String) _title = Value End Set End Property Private _checkedOut As Boolean Public Property CheckedOut() As Boolean Get Return _checkedOut End Get Set(ByVal Value As Boolean) _checkedOut = Value End Set End Property Private _dateOfAcquisition As DateTime Public Property DateOfAcquisition() As DateTime Get Return _dateOfAcquisition End Get Set(ByVal Value As DateTime) _dateOfAcquisition = Value End Set End Property Private _replacementCost As Double Public Property ReplacementCost() As Double Get Return _replacementCost End Get Set(ByVal Value As Double) _replacementCost = Value End Set End Property End Class
Abstraction • Abstraction means ignoring irrelevant features, properties, or functions and emphasizing the relevant ones ... Data Abstraction is the development of classes,objects, types in terms of their interfaces and functionality, instead of their implementation details. • ... relevant to the given project (with an eye to future reuse in similar projects) Abstraction = managing complexity "Relevant" to what? 9
Inheritance Hierarchies • Using inheritance we can create inheritance hierarchies • Easily represented by UML class diagrams • UML class diagrams • Classes are represented by rectangles containing their methods and data • Relations between classes are shown as arrows • Closed triangle arrow means inheritance • Other arrows mean some kind of associations
UML Class Diagram – Example struct interface Shape Point ISurfaceCalculatable #Position:Point +CalculateSurface:float +X:int +Y:int +Point struct Square Rectangle Color -Size:float -Width:float +RedValue:byte -Height:float +GreenValue:byte +Square +BlueValue:byte +CalculateSurface:float +Rectangle +CalculateSurface:float +Color FilledSquare FilledRectangle -Color:Color -Color:Color +FilledSquare +FilledRectangle
Encapsulation • Encapsulation hides the implementation details • Class announces some operations (methods) available for its clients – its public interface • All data members (fields) of a class should be hidden Accessed via properties (read-only and read-write) • No interface members should be hidden • Encapsulation in a nutshell, encapsulation is thehiding of data implementation by restricting access to accessors and mutators. 14
Encapsulation – Example • Data fields are private • Constructors and accessors are defined (getters and setters) Person -name : string -age : TimeSpan +Person(string name, int age) +Name : string { get; set; } +Age : TimeSpan { get; set; } 15
Accessor An accessor is a method that is used to ask an object about itself. In OOP, these are usually in the form of properties, which have, undernormal conditions, a get method, which is an accessor method.However, accessor methods are not restricted to properties and can beany public method that gives information about the state of the object. Public Class Person // use Private class to hide the implementation of the objects . // fullName, which is used for the internal implementation of Person. Private _fullNameAs String = “Raymond Lewallen” /* This property acts as an accessor. To the caller, it hides the implementation of fullName and where it is set and what is setting its value. It only returns the fullname state of the Person object, and nothing more. From another class, calling Person.FullName() will return “Raymond Lewallen”. There are other things, such as we need to instantiate the Person class first, but thats a different discussion. Public ReadOnly Property FullName() As String Get Return _fullName End Get End Property End Class
Mutator Mutators are public methods that are used to modify the state of an object, while hiding the implementation of exactly how the data gets modified. Mutators are commonly another portion of the property discussed above, except this time its the set method that lets the caller modify the member data behind the scenes. Public Class Person //We use Private here to hide the implementation of the objects fullName, which is used for the internal // implementation of Person. Private _fullName As String = “Raymond Lewallen” //This property now acts as an accessor and mutator. We still have hidden the implementation of fullName. Public Property FullName() As String Get Return FullName End Get Set(ByVal value As String) _fullName = value End Set End Property End Class
Data abstraction and encapuslation are closely tied together, because a simple definition of data abstraction is the development of classes, objects, types in terms of their interfaces and functionality, instead of their implementation details Abstraction is used to manage complexity. Software developers use abstraction to decompose complex systems into smaller components. The best definition of abstraction I’ve ever read is: “An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of object and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.”, G. Booch,
4. Polymorphism • Polymorphism means that a variable of a supertype can refer to a subtype object. • Polymorphism is an important Object oriented concept and widely used in Java and other programming language. • Polymorphism in java is supported along with other concept like Abstraction, Encapsulation and Inheritance. • Polymorphism means one name, many forms. • Polymorphism manifests itself by having multiple methods all with the same name, but slighty different functionality.
//Magazine class that inherits LibraryAsset PublicNotInheritable Class Magazine Inherits LibraryAsset End Class //Book class that inherits LibraryAsset Public NotInheritable Class Book Inherits LibraryAsset
Polymorphism • Polymorphism= ability to take more than one form (objects have more than one type) • A class can be used through its parent interface • A child class may override some of the behaviors of the parent class • Polymorphism allows abstract operations to be defined and used • Abstract operations are defined in the base class' interface and implemented in the child classes • Declared as abstract or virtual 21
Polymorphism (2) • Why handle an object of given type as object of its base type? • To invoke abstract operations • To mix different related types in the same collection • E.g. List<object> can hold anything • To pass more specific object to a method that expects a parameter of a more generic type • To declare a more generic field which will be initialized and "specialized" later 22
Polymorphism – Example (2) abstract class Figure { public abstract double CalcSurface(); } abstract class Square { public override double CalcSurface() { return … } } Figure f1 = new Square(...); Figure f2 = new Circle(...); // This will call Square.CalcSurface() int surface = f1.CalcSurface(); // This will call Square.CalcSurface() int surface = f2.CalcSurface();
Inheritance • When OOP allows you to design new classes from existing classes, this process called inheritance. • Inheritance is an important and powerful feature for • reasoning software; • avoid redundancy; • make the system easy to comprehend; • and easy to maintain.
Superclasses & Subclasses • Inheritance enable to define a general class called superclass(parent class) and later extend it to more specialized classes called subclass(child class). Examples are as follow: • We can call “EverGreen Trees” are subclass (child) of the “Trees” superclass(parent). • An “EmployeeWithTerritory” is a child to the “Employee” parent.
Concept of Inheritance After create the Employee class, you can create specific Employee objects, such as the following: Employee receptionist = new Employee(); Employee deliveryPerson = new Employee();
Class Diagram showingEmployee & EmployeeWithTerritory Class diagram showing the relationship between Emplyee and EmployeeWithTerritory. You create a class, EmployeeWithTerritory, and provide the class three field (empNum, empSal & empTerritory) and six methods (get & set methods for each three fields).
Class Diagram showingEmployee & EmployeeWithTerritory cont.. • Efficient alternative is: create class EmployeeWithTerritory so it inherits all the attributes and methods of employee. • Then, you can add just one field and two methods that are within EmployeeWithTerritory objects. • Use inheritance to create derived class • Save time • Reduce errors • Reduce amount of new learning required to use new class
Inheritance Terminology • Base class • Used as a basis for inheritance • Also called: • Superclass, or Parent class (such as Employee) • Derived class • Inherits from a base class • Always “is a” case or example of more general base class • Also called: • Subclass or Child class (Such as EmployeeWithTerritory)
Are superclass’s Constructor Inherited? No. They are not inherited. They are invoked explicitly or implicitly. Explicitly using the super keyword. A constructor is used to construct an instance of a class. Unlike properties and methods, a superclass's constructors are not inherited in the subclass. They can only be invoked from the subclasses' constructors, using the keyword super. If the keyword super is not explicitly used, the superclass's no-arg constructor is automatically invoked.
Superclass’s Constructor Is Always Invoked A constructor may invoke an overloaded constructor or its superclass’s constructor. If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor. For example,
Superclasses and Subclasses The GeometricObject class is the superclass for Circle and Rectangle GeometricObject CircleFromSimpleGeometricObject RectangleFromSimpleGeometricObject TestCircleRectangle Run
SimleGeometricObjectVideo • Video Listing -1 - GeometricObject
Calling Superclass Methods You could rewrite the printCircle() method in the Circle class as follows: public void printCircle() { System.out.println("The circle is created " + super.getDateCreated() + " and the radius is " + radius); }
Overriding Methods in the Superclass A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding. public class Circle extends GeometricObject { // Other methods are omitted /** Override the toString method defined in GeometricObject */ public String toString() { return super.toString() + "\nradius is " + radius; } }
Using the Keyword super The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways: • To call a superclassconstructor • To call a superclass method
Extending Classes • Keyword extends • Achieve inheritance in Java • Example: • public class EmployeeWithTerritory extends Employee • Inheritance is a one-way proposition(plan) • Child inherits from parent, not other way around • Subclasses are more specific • instanceof keyword
The instanceof Operator Use the instanceof operator to test whether an object is an instance of a class: Object myObject = new Circle(); ... // Some lines of code /** Perform casting if myObject is an instance of Circle */ if (myObject instanceof Circle) { System.out.println("The circle diameter is " + ((Circle)myObject).getDiameter()); ... }
Extending Classes (cont'd.) Each EmployeeWithTerritoryautomatically receives the data fields and methods of the superclass Employee, then new fields and methods to the newly created subclass.
Constructor Chaining Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. This is called constructor chaining. public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } }
animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 1. Start from the main method
animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 2. Invoke Faculty constructor
animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 3. Invoke Employee’s no-arg constructor
animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 4. Invoke Employee(String) constructor
animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 5. Invoke Person() constructor
animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 6. Execute println
animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 7. Execute println
animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 8. Execute println
animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 9. Execute println