Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Inheritance and Polymorphism- I Math 130 Introduction to Computer Programming Lecture #27 Monday, November 5, 2007.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
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,
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 10: Inheritance and Polymorphism
Inheritance Chapter 11.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
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.
What is inheritance? It is the ability to create a new class from an existing class.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
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.
Programming in Java CSCI-2220 Object Oriented Programming.
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.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
© 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 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
1 More About Derived Classes and Inheritance Chapter 9.
Chapter 11 Polymorphism. Contents I. Polymorphism 1. Polymorphism 2. Polymorphism and Dynamic Binding 3. The “is-a” Relationship Does Not Work in Reverse.
Chapter 11 Inheritance. Contents I.What Is Inheritance? II. Calling the Superclass Constructor III. Overriding Superclass Methods IV. Protected Members.
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Modern Programming Tools And Techniques-I
Polymorphism Contents Forms of polymorphism
Polymorphism, Abstract Classes & Interfaces
by Tony Gaddis and Godfrey Muganda
Chapter 5 Hierarchies IS-A associations superclasses subclasses
Modern Programming Tools And Techniques-I Inheritance
An introduction to inheritance
Starting Out with Java: From Control Structures through Objects
Chapter 9: Polymorphism and Inheritance
Week 6 Object-Oriented Programming (2): Polymorphism
Polymorphism, Abstract Classes & Interfaces
Java Inheritance.
Chapter 8 Inheritance Part 2.
Final and Abstract Classes
Chapter 11: Inheritance Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Presentation transcript:

Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object class Polymorphism Abstract Classes and Abstract Methods Interfaces

Inheritance The Concept: Inheritance allows a new class to extend an existing class. The new class inherits the public methods and fields of the class that it extends.

An example of inheritance Human Class double Height - double Weight - String Name - int Gender - Date Data of Birth ComputeAge(void) : int + set and get for all the Fields Woman extends Human boolean isPregnant - boolean hasPlayedSoftBall - boolean pageantBefore - boolean cheerLeader int set and get for all class fields + printInfo() : void Man extends Human boolean hasPlayedFootball -boolean hasPlayedBaseball -hasBeardAndMustache set and get for all the Fields + printInfo(void) : void

Let’s create those three classes Human Class Woman Class Man Class See Inheritance Project

Question of the Day Inheritance: “is a” To know if you can use inheritance in your class, ask yourself if your class “is a” of the inherited class Examples: A poodle is a dog A flower is a plant A rectangle is a shape A car is a motor??? How do we know what can be inherited?

Another Example of Inheritance Situation The final grade of students is based on a set of graded activities: All activities generate a score (0-100 points) Each activity has a different way of computing its score Each activity has its weight percentage into the final course grade Graded ActivityHow grade is appliedPercentage of final grade LaboratoryNumber of correctly completed labs25% Midterm ExamNumber of corrected answers35% Final examNumber of correct answers40%

The inheritance tree Graded Activity Class Lab Activity Class Midterm Exam Class Midterm Exam Class Final Exam Class Final Exam Class

Grade Activity Class score : double - percentage : double - activityType : String setScore(s : double) : void + getScore() : double + other setters and getters LaboratoryActivity completedLabs : int - numberOfLabs : int computeScore() Midterm Activity numberOfQuestions : int - numberOfMisses : int computeScore() + getActivityScore() : double + getPercentage FinalExame Activity numberOfQuestions : int - numberOfMisses : int computeScore() + getActivityScore() : double + getPercentage Midterm Activity MidtermActivity( int numberOfMisses, int numberOfQuestions) - sets the percentage - sets the activityType FinalExam Activity FinalExamActivity( int numberOfMisses, int numberOfQuestions) - sets the percentage - sets the activityType Exams Activity numberOfQuestions : int - numberOfMisses : int computeScore() : void + setNumberOfQuestions() + getNumberOfQuestions() + other setters and getters

Let’s refresh our memory about Constructors What does a constructor do? When is a contructor called?

Constructors are created when you use the “new” operation to create new objects from a class blue print ArrayList listOfStudents = new ArrayList( ); You can use constructors to initialize class fields and automatically run methods to initialize whatever is necessary Example: see LaboratoryActivity class Does every class have a constructor? Yes. If you do not create one, Java will create a default contructor with no input arguments public DefaultConstructor( ) { }

Which constructor is called? When you create a new object from a sub-class, like FinalExamActivity, which constructor is called? Is the constructor of the super class called when creating a sub-class object? Hint: Think about in the case that the super class initializes some fields Let’s do a test, let’s modify the GradeActivity project and see what happens…

As you know, a class can have multiple constructors Different signatures (input arguments) If your sub-class needs to execute a specific constructor of the super class then just call it from the sub-class constructor like this: Public SubClass2( ) { super(10); // do your stuff here } If a super class has not default constructor, the sub-class MUST call the super class constructor in its (sub-class) constructor!

11-18 Inheritance, Fields and Methods Members of the superclass that are marked private: are not inherited by the subclass, exist in memory when the object of the subclass is created may only be accessed from the subclass by public methods of the superclass. Members of the superclass that are marked public: are inherited by the subclass, and may be directly accessed from the subclass.

11-19 Inheritance, Fields and Methods When an instance of the subclass is created, the non-private methods of the superclass are available through the subclass object. FinalExam exam = new FinalExam(); exam.setScore(85.0); System.out.println("Score = " + exam.getScore()); Non-private methods and fields of the superclass are available in the subclass. setScore(newScore); See Inheritance Project

Important Points to Remember A sub class can: Call methods from the super class. These methods are inherited by the sub class Can create new methods in its body that the super class does not have These new methods cannot be called by the super class Override existing methods from the super class When calling these methods, Java will use the sub class methods instead of the one from super class

11-22 Overriding Superclass Methods Both overloading and overriding can take place in an inheritance relationship. Overriding can only take place in an inheritance relationship. Example: See Example next slide SuperClass3.java, SuperClass3.java SubClass3.java, SubClass3.java ShowValueDemo.java

11-25 Preventing a Method from Being Overridden The final modifier will prevent the overriding of a superclass method in a subclass. public final void message() If a subclass attempts to override a final method, the compiler generates an error. This ensures that a particular superclass method is used by subclasses rather than a modified version of it.

Example of Final Methods and Fields double i = Math.PI; public static final double PI = ; You do not want anyone to override methods like SINE and COSINE public static final double sin(double a)

11-28 Protected Members Protected members of class: may be accessed by methods in a subclass, and by methods in the same package as the class. Example: GradedActivity2.java FinalExam2.java ProtectedDemo.java

11-29 Access Specifiers ModifierClassPackageSubclassWorld public ✔✔✔✔ protected ✔✔✔✘ no modifier ✔✔✘✘ private ✔✘✘✘

11-31 The Object Class All Java classes are directly or indirectly derived from a class named Object. Object is in the java.lang package. Any class that does not specify the extends keyword is automatically derived from the Object class. public class MyClass { // This class is derived from Object. } Ultimately, every class is derived from the Object class.

11-32 The Object Class Because every class is directly or indirectly derived from the Object class: every class inherits the Object class’s members. example: toString and equals. In the Object class, the toString method returns a string containing the object’s class name and a hash of its memory address. The equals method accepts the address of an object as its argument and returns true if it is the same as the calling object’s address. Example: ObjectMethods.javaObjectMethods.java

The Concept of Polymorphism Shape Rectangle Circle area() perimeter() area() perimeter() area() perimeter() Circle and Rectangle are concrete classes with their own separate implementations of the methods area() and Perimeter() Shape is an abstract class with no implementation of area() and perimeter()

public abstract class Shape { protected String shapeName; public Shape(String name) { shapeName = name; } public abstract double area( ); public abstract double perimeter( ); public String toString( ) { return shapeName; } } The Concept of Polymorphism

public class Rectangle extends Shape { protected double length, width; public Rectangle(double len, double wid { super(“Rectangle”); length = len; width = wid; } public double area() { return length * width; } public double perimeter() { return 2.0 * (length + width); } } public class Circle extends Shape { private double radius; public Circle (double rad) { super (“Circle”); radius = rad; } public double area( ) { return Math.PI * radius * radius; } public double perimeter( ) { return 2.0 * Math.PI * radius; } }

A Listof Shapes A container of Shape objects will execute their own area and perimeter methods The Concept of Polymorphism

public class ShapeShifter { public static void main (String [ ] args) { Shape [ ] shapeList = new Shape[5]; shapeList[0] = new Circle(3.0); shapeList[1] = new Rectangle(3.0, 4.0); shapeList[2] = new Rectangle(2.5, 7.5); shapeList[3] = new Circle(2.5); shapeList[4] = new Square(5.0); for (int i = 0; i < shapeList.length; i++) { System.out.print (shapeList[i].toString( ) + “ ”); System.out.print (shapeList[i].area( ) + “ ”); System.out.println (shapeList[i].perimeter( )); } } } Create an array to hold objects of (derived from) class Shape Create objects of the derived classes and put them in shapeList Iterate through the list and show area and perimeter of shapes Each derived class object executes its own area and perimeter methods The Concept of Polymorphism

11-40 Abstract Class An abstract class cannot be instantiated, but other classes are derived from it. An Abstract class serves as a superclass for other classes. A class becomes abstract when you place the abstract key word in the class definition. public abstract class ClassName

11-41 Abstract Methods An abstract method has no body and must be overridden in a subclass. An abstract method is a method that appears in a superclass, but expects to be overridden in a subclass. Example: See next page Student.java, CompSciStudent.java, CompSciStudentDemo.java Student.javaCompSciStudent.javaCompSciStudentDemo.java

public abstract class Shape { protected String shapeName; public Shape(String name) { shapeName = name; } public abstract double area( ); public abstract double perimeter( ); public String toString( ) { return shapeName; } public class Rectangle extends Shape { protected double length, width; public Rectangle(double len, double wid { super(“Rectangle”); length = len; width = wid; } public double area() { return length * width; } public double perimeter() { return 2.0 * (length + width); } public class Circle extends Shape { private double radius; public Circle (double rad) { super (“Circle”); radius = rad; } public double area() { return Math.PI * radius * radius; } public double perimeter() { return 2.0 * Math.PI * radius; }

11-43 Abstract Methods Notice that the key word abstract appears in the header, and that the header ends with a semicolon. public abstract void setValue(int value); Any class that contains an abstract method is automatically abstract. If a subclass fails to override an abstract method, a compiler error will result. Abstract methods are used to ensure that a subclass implements the method.

Another Examples of the need for abstract classes You made a game that all the animals must jump and make noises However each animal has a different way of jumping and roar. So you abstract the jump and noise methods and whoever creates a new animal must implement those methods You create a pizza recipe program that tells you the steps for creating different types of pizza Since each pizza has different toppings, you abstract the listOfIngridients() method

11-46 Fields in Interfaces An interface can contain field declarations: all fields in an interface are treated as final and static. Because they automatically become final, you must provide an initialization value. public interface Doable { int FIELD1 = 1, FIELD2 = 2; (Method headers...) } Any class that implements this interface has access to these variables.

11-47 Implementing Multiple Interfaces A class can be derived (extended ) from only one superclass. Java allows a class to implement multiple interfaces. When a class implements multiple interfaces, it must provide the methods specified by all of them. To specify multiple interfaces in a class definition, simply list the names of the interfaces, separated by commas, after the implements key word. public class MyClass implements Interface1, Interface2, Interface3

11-48 Interfaces in UML GradedActivity RelatableFinalExam3 A dashed line with an arrow indicates implementation of an interface.

11-49 Polymorphism with Interfaces Java allows you to create reference variables of an interface type. An interface reference variable can reference any object that implements that interface, regardless of its class type. This is another example of polymorphism. Example: RetailItem.java CompactDisc.java DvdMovie.java PolymorphicInterfaceDemo.java

11-50 Polymorphism with Interfaces In the example code, two RetailItem reference variables, item1 and item2, are declared. The item1 variable references a CompactDisc object and the item2 variable references a DvdMovie object. When a class implements an interface, an inheritance relationship known as interface inheritance is established. a CompactDisc object is a RetailItem, and a DvdMovie object is a RetailItem.

11-51 Polymorphism with Interfaces A reference to an interface can point to any class that implements that interface. You cannot create an instance of an interface. RetailItem item = new RetailItem(); // ERROR! When an interface variable references an object: only the methods declared in the interface are available, explicit type casting is required to access the other methods of an object referenced by an interface reference.