Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.

Slides:



Advertisements
Similar presentations
A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
Advertisements

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.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Inheritance and Polymorphism CS180 Fall Definitions Inheritance – object oriented way to form new classes from pre-existing ones –Superclass The.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS 106 Introduction to Computer Science I 11 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
1 Evan Korth New York University abstract classes and casting Professor Evan Korth New York University.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
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.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Chapter 10 Classes Continued
Abstract Classes and Interfaces
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
What is inheritance? It is the ability to create a new class from an existing class.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
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.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Polymorphism in Methods
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Java Programming Language
Java Inheritance.
Chapter 9 Carrano Chapter 10 Small Java
Chapter 8 Class Inheritance and Interfaces
Agenda Inheritance Polymorphism Type compatibility Homework.
Presentation transcript:

Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes 6.Interfaces 7.The Comparable Interface

Inheritance Superclasses and Subclass – Inheritance defines a relationship between objects that share characteristics. Subclass – is created from an existing superclass. Subclass inherits charatceristics of its superclass. Subclass is bigger than a superclass – it contains more data and more methods. Allows you to reuse code over and over gain.

Inheritance Hierarchy Inheritance hierarchy – when a subclass itself is a superclass for another subclass. ***Note Arrow points to its superclass Person StudentEmployee GradStudentUnderGrad

Is-a Relationship Arrow designates an is-a relationship. There needs to be an is-a relationship when working with inheritance. Example: – An Employee is-a Person – Student is-a Person – GradStudent is-a Student Opposite is not true – Person doesn’t always have to be an Employee The subclass inherits all public variables and methods of the superclass, but does not inherit the constructors even though they are public.

Method Overriding When the subclass and superclass has the exact same method in each of their class. The subclass method will override the superclass method. To run the superclass method, you must use the keyword super which will be discussed later.

extends Keyword In the subclass, you must use the extends keyword to inherit the superclass methods and variables. – Example: public class Subclass extends Superclass { } You can only extend one class at a time A Parent class (superclass) can have multiple children classes (subclasses) but a child class can only have one parent class.

Protected There is a protected specifier along with public and private Not part of the AP Subset All protected variables and methods are inherited.

Super keyword Subclass methods overrides superclass methods with the same method heading signatures. Super allows you to undo the override. By using super.methodName() allows you to run the method of the superclass over its subclass method.

Super & Constructors Constructors are never inherited Be sure to provide at least one constructor when you write a subclass. Constructors are never inherited from the superclass. If the superclass does not have a default constructor but does have a constructor with parameters, creating a subclass without constructors will cause an error. To run the constructor of the superclass, just use super() by itself.

Super examples public GradStudent() { super(); myGradId = 12345; } Example public GradStudent(String name,String grade, int id) { super(name,grade); myGradId = id; } If super is used in the implementation of a subclass constructor, it must be used in the first line of the constructor body. If no constructor is provided in a subclass, the compiler provides the following default constructor public Subclass() { super(); }

Rules for Subclasses A subclass can add new private instance variables A subclass can add new public, private, and static methods A subclass can override inherited methods A subclass may not redefine a public methods of the superclass. A subclass should define its own constructors A subclass cannot directly access the private members of its superclass. It must use accessor or mutator methods.

Declaring Subclass Objects When a variable of a superclass is declared in a client program, that reference can refer not only to an object of the superclass, but also to objects of any of its subclasses. – Example: Student s = new Student(); Student g = new GradStudent(); Student u = new UnderGrad(); This works because a GradStudent is-a Student, and an UnderGrad is-a Student.

Not Valid Note that since a Student is not necessarily a GradStudent nor an UnderGrad, the following declarations are not valid: – GradStudent g = new Student(); – UnderGrad u = new Student();

Example Student s = new Student(); Student g = new GradStudent(); Student u = new UnderGrad(); Suppose a method called setGrade() is in the Student class. s.setGrade(“pass”); will work because it is in the Student class. g.setGrade(“pass”); & u.setGrade(“pass”); will work because inheritance.

Bad calls Suppose getID() is in the GradStudent class. int studnum = s.getId(); int unstudnum = u.getId(); Neither Student s nor UnderGrad u inherit the getID() method from the GradStudent class. A superclass does not inherit from the subclass.

Polymorphism Student s = new Student(); Student g = new GradStudent(); Student u = new UnderGrad(); The method computeGrade() is all classes (Student, GradStudent, UnderGrad) The following are legal because they all have been declared Student. s.computeGrade(); g.computeGrade(); u.computeGrade(); The question is which computeGrade() method will run.

Polymorphism A method that has been overridden in at least one subclass is said to be polymorphic. Polymorphism is the mechanism of selecting the appropriate method for a particular object in a class hierarchy. Selected during runtime. The correct method is chosen because, in Java, method calls are always determined by the type of the actual object (GradStudent or UnderGrad), not the type of the object reference (Student). The previous slide computeGrade() will all perform the correct operations for their particular instances(Student, GradStudent, & UnderGrad objects s,g,u).

Dynamic Binding (Late Binding) Making a runtime decision about which instance method to call is known as dynamic binding or late binding (method overriding). Static binding or early binding is done at compile time. (method overloading) compares method signatures. In polymorphism, the actual method that will be called is not determined by the compiler. Example: – The compiler determines if a method can be called(is it legal?). While the run-time environment determines how it will be called(which overridden form should be used?). Polymorphism applies only to overridden methods in subclasses.

Type Compatibility Suppose method getId() only exist in the GradStudent class. Student s = new GradStudent(); GradStudent g = new GradStudent(); int x = s.getId(); //ERROR int y = g.getId(); //Legal Both s and g represent GradStudent objects, so why does s.getId() cause an error?? The reason is that s is of type Student, and the Student class doesn’t have a getId() method. Remember getId() method is only in UnderGrad and not Student so this is not Polymorphism because no method is being overridden.

Downcasting You can fix the other slide problem by Downcasting. int x =((GradStudent)s).getId(); Since s (of type Student) is actually representing a GradStudent object, such as a cast can be carried out. Casting a superclass to a subclass type is called Downcasting. Notice the parenthesis are necessary around the s. An Error would occur if lefty out. Dot operator has a higher precedence than a cast.

Rules for Polymorphic Method Calls a.method(b) For a declaration like: Superclass a = new Subclass(): The type of a at compile tie is Superclass; at run time it is Subclass At compile time, method must be found in the class of a, that is, in Superclass. (this is true whether the method is polymorphic or not) If method cannot be found in the class of a, you need to do an explicit cast on a to its actual type. For a polymorphic method, at run time the actual type of a is determined – Subclass in this example – and method is selected from Subclass. This could be an inherited method if there is no overriding method. The type of parameter b is checked at compile time. You may need to do an explicit cast to the subclass type to make this correct. Method selected by type of “a” at run time Parameter b must be of correct type at compile type

The ClassCastException The ClassCastException is a run-time exception thrown to signal an attempt to cast an object to a class of which it is not an instance. Examples: Student u = new UnderGrad(); System.out.println((String)u); //ClassCastException u is not a String int x = ((GradStudent)u).getID();// ClassCastException u is not an //instance of GradStudent

Abstract Classes Abstract class are declared with keyword abstract in the header. An abstract class is a superclass that represents an abstract concept, and therefore should not be instantiated. An abstract class may contain abstract methods. – An abstract method has no implementation code, just a header and ends with a semicolon “;” – Every subclass will need to override the abstract method of the Superclass. If a class contains any abstract methods, it must be declared an abstract class.

Abstract Classes If a subclass of an abstract class does not provide implementation code for all the abstract methods of its superclass, it too becomes an abstract class and must be declared as such to avoid a compile-time error. An abstract class can have both abstract methods and concrete methods (nonabstract methods) It is possible for an abstract class to have no abstract methods Abstract class may or may not have constructors You can not create an instance of an abstract class Polymorphism works with abstract classes as it does with concrete classes. (non abstract class)

Interfaces An interface is a collection of related methods whose headers are provided without implementations. (simply put a class of all abstract methods) All of the methods are public and abstract – there is no need to explicitly include public and abstract keywords. Classes can implement the interface by using the keyword “implements” Example of interface class: public interface FlyingObjetcs { void fly(); Boolean isFlying(); } Example on a class implementing an Interface public class Bird implements FlyingObject ***Note: Class Bird must have the code for methods fly() & isFlying()

implements Keyword You can implement an Interface and extend a class at the same time. Example: Public class Mosquito extends Insect implements FlyingObject Notes: – The extends clause must precede the implements clause. – A class can have just one superclass, but it can implement any number of interfaces: public class Subclass extends Superclass implements Interface1, Interface2 …

Comparable Interface java.lang package contains the Comparable interface, which provides a useful method for comparing objects. Classes written for objects that need to be compared should implement Comparable. – Example: public interface Comparable { int compareTo(Object obj); } ***Note any class that implements Comparable must provide a compareTo method that returns a 0, negative or positive. If the objects being compared are not type compatible, a ClassCastException is thrown by the method

Abstract Class vs Interface Use an abstract class for an object that is application specific, but incomplete without its subclasses. Consider using an interface when its methods are suitable for your program, but could be equally applicable in a variety of programs An interface cannot contain instance variables, whereas an abstract class can. An interface and an abstract class can both declare constants. It is not possible to create an instance of an interface object or an abstract class object