Chapter 11 Inheritance. Contents I.What Is Inheritance? II. Calling the Superclass Constructor III. Overriding Superclass Methods IV. Protected Members.

Slides:



Advertisements
Similar presentations
Starting Out with Java: From Control Structures through Objects
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
OOP: Inheritance By: Lamiaa Said.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Inheritance and Polymorphism.
Inheritance and Polymorphism- I Math 130 Introduction to Computer Programming Lecture #27 Monday, November 5, 2007.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Inheritance, Polymorphism, and Virtual Functions
Chapter 10 Classes Continued
Inheritance Chapter 11.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Intro to OOP with Java, C. Thomas Wu
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object.
11-1 Chapter.9 Classes & Objects: Inheritance –What Is Inheritance? –Calling the Superclass Constructor –Overriding Superclass Methods –Protected Members.
AN INTRODUCTION TO INHERITANCE. In your group Define 5 attributes that you would use to describe persons. Define 3 different attributes that can describe.
© 2012 Pearson Education, Inc. All rights reserved. Chapter 11: Inheritance Starting Out with Java: From Control Structures through Data Structures Second.
Chapter Topics Chapter 10 discusses the following main topics:
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 11: Inheritance Starting Out with Java: From Control Structures.
Inheriatance. 9-2 What is Inheritance? Generalization vs. Specialization Real-life objects are typically specialized versions of other more general objects.
More on Inheritance Chapter 11 Continued. Reminders Overloading – different signatures Overriding – same signatures Preventing overriding – use final.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
11-2  What Is Inheritance?  Calling the Superclass Constructor  Overriding Superclass Methods  Protected Members  Chains of Inheritance  The Object.
CSC 205 Java Programming II Inheritance Inheritance In the real world, objects aren’t usually one-of-a-kind. Both cars and trucks are examples of.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects.
Creating Classes from Other Classes Appendix D © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
OOP: Inheritance. Inheritance A class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley What Is Inheritance? 15.1.
© 2010 Pearson Addison-Wesley. All rights reserved. AN INTRODUCTION TO INHERITANCE.
Inheritance Chapter 11 in Gaddis. Is a relationships in ‘real’ life Exist when one object is a specialized version of another one –Examples An english.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
Chapter 11 Polymorphism. Contents I. Polymorphism 1. Polymorphism 2. Polymorphism and Dynamic Binding 3. The “is-a” Relationship Does Not Work in Reverse.
Inheritance and Polymorphism
Inheritance.
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Chapter 11 Inheritance and Polymorphism
Python First Edition STARTING OUT WITH Chapter 10 Inheritance
Final and Abstract Classes
Polymorphism, Abstract Classes & Interfaces
Inheritance and Polymorphism
OBJECT ORIENTED PROGRAMMING II LECTURE 7 GEORGE KOUTSOGIANNAKIS
Inheritance, Polymorphism, and Virtual Functions
by Tony Gaddis and Godfrey Muganda
Road Map Inheritance Class hierarchy Overriding methods Constructors
An introduction to inheritance
Starting Out with Java: From Control Structures through Objects
Chapter 9 Inheritance and Polymorphism
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Chapter 9 Object-Oriented Programming: Inheritance
Lecture 22 Inheritance Richard Gesick.
Chapter 9: Polymorphism and Inheritance
Inheritance, Polymorphism, and Virtual Functions
Week 6 Object-Oriented Programming (2): Polymorphism
Polymorphism, Abstract Classes & Interfaces
Java – Inheritance.
Java Inheritance.
Chapter 11 Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Chapter 11: Inheritance Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

Chapter 11 Inheritance

Contents I.What Is Inheritance? II. Calling the Superclass Constructor III. Overriding Superclass Methods IV. Protected Members V. Chains of Inheritance VI. The Object Class

I. What is Inheritance? 1. Generalization and Specialization 2. Inheritance and the “Is a” Relationship 3. Inheritance in UML Diagram 4. An Example: Graded Activities 5. Superclass's Constructor 6. Inheritance Does Not Work In Reverse

I.1 Generalization and Specialization In real world we can find many objects that are specialized versions of other more general objects. Insect: Describes a very general type of creature with numerous characteristics. Grasshoppers and bumblebees are insects. They have all the general characteristics of an insect. In addition, Grasshoppers and bumblebees have special characteristics of their own. For example, The grasshopper has its jumping ability. The bumblebee has its stinger. Grasshoppers and bumblebees are specialized versions of an insect.

I.1 Generalization and Specialization Insect All insects have certain characteristics. In addition to the common insect characteristics, the grasshopper has its own unique characteristics such as the ability to jump. In addition to the common insect characteristics, the bumblebee has its own unique characteristics such as the ability to sting.

I.2 Inheritance and the “Is a” Relationship When one object is a specialized version of another object, there is an “is a” relationship between them. A grasshopper is an insect. A poodle is a dog. A car is a vehicle. A flower is a plant. A rectangle is a shape. A football player is an athlete.

I.2 Inheritance and the “Is a” Relationship When an “is a” relationship exists between objects, it means that the specialized object has: All of the characteristics of the general object Additional characteristics that make it special. In object-oriented programming, inheritance is used to created an “is a” relationship among classes. This allows us to extend the capabilities of a class by creating another class that is a specialized version of it.

I.2 Inheritance and the “Is a” Relationship Inheritance involves a superclass (base class) and a subclass (derived class). The superclass is the general class. The subclass is the specialized class. The subclass is an extended version of the superclass. The subclass inherits fields and methods from the superclass without any of them having to be rewritten. New fields and methods may be added to the subclass, and that is what makes it a specialized version of the superclass.

I.3 Inheritance in UML Diagram Inheritance is shown in a UML diagram by connecting two classes with a line that has a open arrowhead at one end. The arrowhead points to the superclass.

I.4 An Example: Graded Activities Most teachers assign various graded activities for their students to complete. A graded activity can be given a numeric score such as 70, 90, and so on, and a letter grade such as A, B, C, D, or F.

I.4 An Example: Graded Activities Many different types of graded activities exist such as Quizzes Midterm exams Final exams Lab reports Essays …

I.4 An Example: Graded Activities The GradedActivity class is designed to hold the numeric score of a graded activity. The GradedActivity class represents the general characteristics of a student's graded activities.

I.4 An Example: Graded Activities Because the numeric scores might be determined differently for each of these graded activities, we can created subclasses to handle each one. The FinalExam class is a subclass of the GradedActivity class. It has fields for The number of questions on the exam The number of points each question is worth The number of questions missed by the student

I.4 An Example: Graded Activities

The extends keyword Indicates that a class (a subclass) extends another class (a superclass) public class FinalExam extends GradedActivity Class being declared (the subclass) Superclass

I.4 An Example: Graded Activities Because the FinalExam class extends the GradedActivity class, it inherits all of the public members of the GradedActivity class. Members of the FinalExam class: Fields: int numQuestions; Declared in FinalExam double pointsEach; Declared in FinalExam int numMissed; Declared in FinalExam The GradedActivity class's score field is not listed among the members of the FinalExam class because the score field is private.

I.4 An Example: Graded Activities Methods in the FinalExam class ConstructorDeclared in FinalExam getPointsEach Declared in FinalExam getNumMissed Declared in FinalExam setScore Inherited from GradedActivity getScore Inherited from GradedActivity getGrade Inherited from GradedActivity

I.4 An Example: Graded Activities Private members of the superclass cannot be accessed by the subclass, so technically speaking, they are not inherited. When an object of the subclass is created, the private members of the superclass exist in memory, but only methods in the superclass can access them. They are truly private to the superclass. numQuestions pointsEach numMissed score A FinalExam object A GradedActivity object

I.4 An Example: Graded Activities When a subclass extends a superclass, the public members of the superclass become public members of the subclass. The superclass constructors are not inherited because their purpose is to construct objects of the superclass.

I.5 The Superclass's Constructor In an inheritance relationship, the superclass constructor always executes before the subclass constructor. When an object of FinalExam class is created, the GradedActivity class's default constructor is executed just before the FinalExam constructor is executed.

I.5 The Superclass's Constructor An example

I.5 The Superclass's Constructor

If a superclass has either (a) a default constructor or (b) a no-arg constructor that was written into the class, then that constructor will be automatically called just before a subclass constructor executes.

I.6 Inheritance Does Not Work In Reverse In an inheritance relationship, the subclass inherits members from the superclass, not the other way around. It is not possible for a superclass to call a subclass's method.

Checkpoint 11.1 Here is the first line of a class header. What is the name of the superclass? What is the name of the subclass? public class Truck extends Vehicle 11.2 Look at the following class declarations and answer the questions that follow them:

Checkpoint public class Shape { private double area; public void setArea(double a) { area = a; } public double getArea() { return area; } } public class Circle extends Shape { private double radius; public void setRadius(double r) { radius = r; setArea(Math.PI * r * r); } public double getRadius() { return radius; } }

Checkpoint a. Which class is the superclass? Which class is the subclass? b. Draw a UML diagram showing the relationship between these two classes. c. When a Circle object is created, what are its public members? d. What members of the Shape class are not accessible to the Circle class's methods?

Checkpoint e. Assume a program has the following declarations: Shape s = new Shape(); Circle c = new Circle(); Indicate whether the following statements are legal or illegal: c.setRadius(10.0); s.setRadius(10.0); System.out.println(c.getArea); System.out.println(s.getArea);

Checkpoint 11.3 Class B extends class A. Describe the order in which the class's constructors execute when a class B object is created.

II. Calling the Superclass Constructor How to call a superclass constructor explicitly? The super keyword refers to an object's superclass. We can use the super keyword to call a superclass constructor explicitly. The super keyword can be used to access members of the superclass.

II. Calling the Superclass Constructor Here are three guidelines about calling a superclass constructor: The super statement that calls the superclass constructor may be written only in the subclass's constructor. The super statement that calls the superclass constructor must be the first statement in the subclass's constructor. This is because the superclass's constructor must execute before the code in the subclass's constructor executes.

II. Calling the Superclass Constructor If a subclass constructor does not explicitly call a superclass constructor, Java will automatically call the superclass's default constructor, or no-arg constructor, just before the code in the subclass's constructor executes. This is equivalent to placing the following statement at the beginning of a subclass constructor: super(); If a superclass does not have a default constructor and does not have no-arg constructors, then a class that inherits from it must call one of the constructors that the superclass does have.

Checkpoint 11.4 Look at the following classes: public class Ground { public Ground() { System.out.println(“You are on the ground.”); } } public class Sky extends Ground { public Sky() { System.out.println(“You are in the sky.”); } } What will the following program display? public class Checkpoint { public static void main(String[] args) { Sky object = new Sky(); } }

Checkpoint 11.5 Look at the following classes: public class Ground { public Ground() { System.out.println(“You are on the ground.”); } public Ground(String groundColor) { System.out.println(“The ground is ” + groundColor); } }

Checkpoint public class Sky extends Ground { public Sky() { System.out.println(“You are in the sky.”); } public Sky(String skyColor) { super(“green”); System.out.println(“The sky is ” + skyColor); } } What will the following program display? public class Checkpoint { public static void main(String[] args) { Sky object = new Sky(“Blue”); } }

III. Overriding Superclass Methods A subclass may have a method with the same signature as a superclass method. In such a case, the subclass method overrides the superclass method. Why do we need to override a superclass method? The method is inadequate for the subclass's purpose. The subclass is more specialized than the superclass, it is sometime necessary for the subclass to replace inadequate superclass methods with more suitable ones.

The CurvedActivity Class Suppose a teacher wants to curve a numeric score before the letter grade is determined. Dr. Harrison determines that in order to curve the grades in her class she must multiply each student's score by a certain percentage. We design a new class, CurvedActivity, which extends the GradedActivity class and has its own specialized version of the setScore method. The setScore method in the subclass overrides the setScore method in the superclass. The rawScore field holds the student's unadjusted score. The percentage field holds the value that the unadjusted score must be multiplied by to get the curved score.

The CurvedActivity Class

Overloading versus Overriding There is a distinction between overloading and overriding. Overloading is when a method has the same name as one or more other methods, but a different parameter list. When a method overrides another method, they both have the same signature. Both overloading and overriding can take place in an inheritance relationship. Overloaded methods can appear within the same class. In addition, a method in a subclass can overload a method in the superclass. Overriding, on the other hand, can only take place in an inheritance relationship. A method can not override another method in the same class.

Overloading versus Overriding If two methods have the same name but different signatures, they are overloaded. This is true where the methods are in the same class or where one method is in the superclass and the other is in the subclass. If a method in a subclass has the same signature as a method in the superclass, the subclass method overrides the superclass method.

Calling an Overridden Superclass Method in the Subclass In order to call the overridden superclass method, we would have use the super keyword in the subclass method. public void showValue(int arg) { super.showValue(arg); //Call the superclass method System.out.println(“SUBCLASS: The int argument was “ + arg); }

Preventing a Method from Being Overridden When a method is declared with the final modifier, it cannot be overridden in a subclass. public final void message() If a subclass attempts to override a final method, the compiler generates an error. This technique can be used to make sure that a particular superclass method is used by subclass and not a modified version of it.

Checkpoint 11.6 Under what circumstances would a subclass need to override a superclass method? 11.7 How can a subclass method call an overridden superclass method? 11.8 If a method in a subclass has the same signature as a method in the superclass, does the subclass method overload or override the superclass method?

Checkpoint 11.9 If a method in a subclass has the same name as a method in the superclass, but uses a different parameter list, does the subclass method overload or override the superclass method? How do you prevent a method from being overridden?

IV. Protected Members Protected members of a class may be accessed by methods in a subclass, and by methods in the same package as the class. A protected member is not quite private, because it may be accessed by some methods outside the class. Protected members are not quite public because access to them is restricted to methods in the same class, subclasses, and classes in the same package as the member's class. A protected member's access is somewhere between private and public.

The GradedActivity2 Class The GradedActivity2 class is a modification of the GradedActivity class. The score field was made protected instead of private.

The GradedActivity2 Class

IV. Protected Members Although making a class member protected instead of private might make some tasks easier, we should avoid this practice when possible. Why ? Because any class that inherits from the class, or is in the same package, has unrestricted access to the protected member. It is always better to make all fields private and then provide public methods for accessing those fields.

Package Access If a class member is not provided an access specifier, it is given package access by default. This means that any method in the same package may access the member. public class Circle { double radius; //Package access int centerX, centerY; //Package access.... }

Package Access There is a subtle difference between protected access and package access. Protected members may be accessed by methods in: the same package a subclass (this is true even if the subclass is in a different package) Members with package access cannot be accessed by subclasses that are in a different package.

Package Access Accessibility from within the class's package Accessibility from outside the class's package

Checkpoint When a class member is declared as protected, what code may access it? What is the difference between private members and protected members? Why should you avoid making class members protected when possible? What is the difference between private access and package access? Why is it easy to give package access to a class member by accident?

V. Chains of Inheritance A superclass can also inherit from another class: A chains of inheritance

The PassFailActivity Class The PassFailActivity class, which is inherits from the GradedActivity class, is intended to determine a letter grade of 'P' for passing, or 'F' for failing. The minPassScore field holds the minimum passing grade for the activity. The getGrade method overrides the superclass method of the same name.

The PassFailExam Class The PassFailExam class, which inherits from the PassFailActivity class, is intended to determine a passing or failing grade for an exam.

The PassFailActivity Class

Class Hierarchies Classes often are depicted graphically in a class hierarchy. A class hierarchy shows the inheritance relationships between classes.

VI. The Object Class Every class in Java, including the ones in the API and the classes that we create, directly or indirectly inherits from a class named Object. When a class does not use the extends keyword to inherit from another class, Java automatically extends it from the Object class. public class MyClasspublic class MyClass extends Object {{ }}

VI. The Object Class Because every class directly or indirectly extends the Object class, every class inherits the Object class's members. Two of the most useful methods are the toString and equals methods. toString() : returns a reference to a String containing the object's class name, followed by sign, followed by the object's hash code (a hexadecimal number) equals() : accepts a reference to an object as its argument. It returns true if the argument references the calling object. If we wish to change the behavior of them for a given class, we must override them in the class.

Checkpoint Look at the following definition: public class D extends B {.... } Because D inherits from B, is it true that D does not inherit from the Object class? Why or why not? When you create a class, it automatically has a toString method and an equals method. Why?