CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.

Slides:



Advertisements
Similar presentations
Chapter 13 - Inheritance. Goals To learn about inheritance To learn about inheritance To understand how to inherit and override superclass methods To.
Advertisements

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.
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Inheritance Part I. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
I NHERITANCE Chapter 10. I NHERITANCE Mechanism for enhancing existing classes You need to implement a new class You have an existing class that represents.
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
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.
CS 106 Introduction to Computer Science I 11 / 19 / 2007 Instructor: Michael Eckmann.
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.
CS 106 Introduction to Computer Science I 04 / 21 / 2010 Instructor: Michael Eckmann.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Programming Languages and Paradigms Object-Oriented Programming.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Chapter 8 More Object Concepts
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Writing Classes (Chapter 4)
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Programming Pillars Introduction to Object- Oriented Programming.
What is inheritance? It is the ability to create a new class from an existing class.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
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.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Object Oriented Programming
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Creating Classes from Other Classes Appendix D © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Classes, Interfaces and Packages
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
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.
Inheritance & Method Overriding BCIS 3680 Enterprise Programming.
CS 116 Object Oriented Programming II Lecture 9 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
OBJECT ORIENTED PROGRAMMING II LECTURE 7 GEORGE KOUTSOGIANNAKIS
An Introduction to Inheritance
Creating and Using Classes
CSC 205 Java Programming II
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Chapter 9 Object-Oriented Programming: Inheritance
Java Programming Language
Lecture 22 Inheritance Richard Gesick.
CIS 199 Final Review.
Presentation transcript:

CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer

This Lecture ’s topics Inheritance Concepts Inheritance Design – Inherited Members of a Class – Subclass Constructors – Overriding Inherited Methods 2

University Community Registry 3 Faculty Name Age ID Academic Dept. Courses taught Staff Name Age ID Office Graduate Student Name Age ID Major TA (Y/N) Degree (MS/PhD) Undergraduate Student Name Age ID Major Minor Dorm resident (Y/N)

University Community Registry 4 public class Faculty{ public String Name; public int age; public String ID; public String Academic Dept; public String [] Courses; //helper methods } public class Staff{ public String Name; public int age; public String ID; public String office; //helper methods } public class GradStudent{ public String Name; public int age; public int ID; public String Major; public String Degree; public boolean TA; //helper methods } public class UgStudent{ public String Name; public int age; public int IIT-ID; public String Major; public String minor; public boolean dorm-resident; //helper methods } Need to define and use a lot of classes! Can we do better? Using public class attributes is not good practice. I used here for simplification

University Community Registry 5 public class Faculty{ public String Name; public int age; public String ID; public String Academic Dept; public String [] Courses; //helper methods } public class Staff{ public String Name; public int age; public String ID; public String office; //helper methods } public class GradStudent{ public String Name; public int age; public int ID; public String Major; public String Degree; public boolean TA; //helper methods } public class UgStudent{ public String Name; public int age; public int IIT-ID; public String Major; public String minor; public boolean dorm-resident; //helper methods } These classes store some common information –i.e. have common attributes.

University Community Registry 6 public class CommunityMember{ public String Name; public int age; public String ID; } Wouldn’t it be great if we could reuse the code in class CommunityMember for the other classes such as Faculty, GradStudent, etc.? Classes Faculty, GradStudent, etc. are actually a specialization of the class CommunityMember

University Community Registry We can reuse code using a method called inheritance 7 public class CommunityMember{ public String Name; public int age; public String ID; } public class Faculty extends CommunityMember{ public String Academic Dept; public String [] Courses; //helper methods } public class Staff extends CommunityMember{ public String office; //helper methods } Use the keyword “extends” for inheriting the code from class CommunityMember

University Community Registry Depending on the accessmodifiers, subclass can access the attributes and methods of superclass 8 class CommunityMember{ public String Name; public int age; public String ID; } class Faculty extends CommunityMember{ public String Academic Dept; public String [] Courses; public printAge(){ System.out.println(“Age: ” + this.age); } Access the “age” attribute defined for CommunityMember class

University Community Registry 9 public class CommunityMember{ public String Name; public int age; public String ID; } public class Faculty extends CommunityMember{ public String Academic Dept; public String [] Courses; //helper methods } Since Faculty inherits or reuses the code from CommunityMember, Faculty is called the subclass of CommunityMember Since CommunityMember provides attributes and methods for Faculty, CommunityMember is called the superclass of CommunityMember

University Community Registry 10 public class GradStudent{ public String Name; public int age; public int ID; public String Major; public String Degree; public boolean TA; //helper methods } public class UgStudent{ public String Name; public int age; public int IIT-ID; public String Major; public String minor; public boolean dorm-resident; //helper methods } Inherit from class CommunityMember public class CommunityMember{ public String Name; public int age; public String ID; } public class Student extends CommunityMember{ public String Major; }

University Community Registry 11 public class CommunityMember{ public String Name; public int age; public String ID; } public class Student extends CommunityMember{ public String Major; } public class GradStudent extends Student{ public String Degree; public boolean TA; //helper methods } public class UgStudent extends Student{ public String minor; public boolean dorm-resident; //helper methods }

Specifying Inheritance The syntax for defining a subclass is to use the extends keyword in the class header, as in: accessModifier class SubclassName extends SuperclassName { // class definition } The superclass name specified after the extends keyword is called the direct superclass As mentioned, a subclass can have many superclasses, but only one direct superclass 12

Inheritance Concepts A common form of reuse of classes is inheritance We can organize classes into hierarchies of functionality The class at the top of the hierarchy (superclass) defines instance variables and methods common to all classes in the hierarchy We derive a subclass, which inherits behavior and fields from the superclass 13

What is the Advantage? If Class B inherits Class A then: – All the methods that class A has are also members of Class B. – All public instance variables of Class A are also members of Class B. – That means that Class B can use these public members of Class A without using an object of Class A to invoke them. In this example Class A is called the SUPERCLASS and Class B is called the SUBCLASS 14

Direct Superclass Class C Class A Class B Class B is the Direct Superclass Class A inherits from Class B but it also inherits indirectly Class C. 15

Superclasses and Subclasses A superclass can have multiple subclasses Subclasses can be superclasses of other subclasses A subclass can inherit directly from only one superclass- – Multiple inheritance is not allowed in Java (C++ allows multiple inheritance). All classes inherit from the Object class 16

Multiple Inheritance The concept of multiple inheritance is shown below (even though Java does not allow it). Class AClass BClass C Class D 17

Multiple Inheritance In the examples thus far we used Single Inheritance: – That means that a subclass can only inherit from a one superclass. Multiple Inheritance means that a subclass can inherit from more than one superclass. – Some languages allow that (i.e. C++). – Java DOES Not allow it. 18

A Sample Vehicle Hierarchy This hierarchy is depicted using a Unified Modeling Language (UML) diagram. In UML diagrams, arrows point from the subclass to the superclass. 19

Superclasses and Subclasses A big advantage of inheritance is that we can write code that is common to multiple classes once and reuse it in subclasses A subclass can define new methods and instance variables, some of which may override (hide) those of a superclass Remember that the subclass gets to use the methods of its superclass as if they were its own (just call them without using an object to invoke them) 20

When Do We have Inheritance? We have inheritance if a “is a” relationship exists between classes. For instance, assume that we have the class Auto. If we were to create a new class called SUV then we can say that SUV is an Auto. Therefore our new class SUV could inherit the class Auto. 21

Inheritance Rules (public) Superclass Members Inherited by subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass? public fieldsyesyes, by using field name yes public methodsyesyes, by calling method from subclass methods yes 22

Inheritance Rules (private) Superclass Members Inherited by subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass? private fieldsnono, must call public accessors and mutators private methodsno 23 Super class members declared as private are not inherited, although they are part of the subclass.

Inheritance Rules (protected) Superclass Members Inherited by subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass? protected fieldsyesyes, by using field name no, must call accessors and mutators protected methods yesyes, by calling method from subclass methods no 24 protected members are inherited by subclasses (like public members), while still being hidden from client classes (like private members). Also, any class in the same package as the superclass can directly access a protected field, even if that class is not a subclass.

protected Members Disadvantage: – Because more than one class can directly access a protected field, protected access compromises encapsulation and complicates maintenance. – For that reason, we prefer to use private, rather than protected, for our instance variables. 25

Inheritance Rules for Constructors Superclass Members Inherited by subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass Using a Subclass Reference? constructorsnoyes, using super( arg list ) in a subclass constructor no 26

Subclass Constructors Constructors are not inherited. However, the subclass can call the constructors of the superclass to initialize inherited fields. Implicit invocation – The default constructor of the subclass automatically calls the default constructor of the superclass. For explicit invocation, use this syntax: super( argument list ); If used, this statement must be the first statement in the subclass constructor. 27

Overriding Inherited Methods A subclass can override (or replace) an inherited method by providing a new version of the method. The signature of the new version must match the inherited method. When the client calls the method, it will call the subclass version. The superclass method is invisible to the client of the subclass, but the subclass methods can still call the superclass method using this syntax: super.methodName( argument list ) 28

Do not confuse overriding a method with overloading a method. Overriding a method: – A subclass provides a new version of that method (same signature), which hides the superclass version from the client. Overloading a method: – A class provides a version of the method, which varies in the number and/or type of parameters (different signature). A client of the class can call any of the public versions of overloaded methods. Common Error Trap 29

The Bank Account Example 30 Note 1: + indicates public and – indicates private Note 2: return types Are shown after the Name and arguments listing of a method Remember, all classes inherit the object class See Example 10.1 BankAccount.java

The BankAccount Class The BankAccount class is the superclass. – Instance variables: balance (double) MONEY (a constant DecimalFormat object) – Methods: Default and overloaded constructors deposit and withdraw methods balance accessor toString See Example 10.1 BankAccount.java 31

The CheckingAccount Class We derive the CheckingAccount subclass from BankAccount: public class CheckingAccount extends BankAccount { } A subclass inherits the public members of a superclass (except constructors). Thus, the CheckingAccount class inherits – the MONEY instance variable – The getBalance, deposit, withdraw, and toString methods See Example 10.2 CheckingAccount.java and Example 10.3 CheckingAccountClient.java 32

private Members Thus, a balance instance variable is allocated to all CheckingAccount objects, but methods of the CheckingAccount class cannot directly access balance. To set or get the value of balance, the CheckingAccount methods must call the withdraw, deposit, or getBalance methods. This simplifies maintenance because the BankAccount class enforces the data validation rules for balance. 33

CheckingAccount Constructors public CheckingAccount( ) { // optional explicit call // to BankAccount default constructor super( ); } public CheckingAccount( double startBalance ) { // explicit call to BankAccount // overloaded constructor super( startBalance ); } See Examples 10.4, 10.5, and

Common Error Trap An attempt by a subclass to directly access a private field or call a private method defined in a superclass will generate a compiler error. – To set initial values for private variables, call the appropriate constructor of the direct superclass. For example, this statement in the overloaded CheckingAccount class constructor calls the overloaded constructor of the BankAccount class: super( startBalance ); 35

SOFTWARE ENGINEERING TIP Overloaded constructors (same as non default constructors) in a subclass should explicitly call the direct super class constructor to initialize the fields in its super classes. 36

The BankAccount Heirarchy 37 Note 1: + indicates public and – indicates private Note 2: return types Are shown after the Name and arguments listing of a method

Adding Specialization A subclass can define new fields and methods that the superclass does not have. That is called specialization. Our CheckingAccount class adds – these instance variables: monthlyFee, a double DEFAULT_FEE, a double constant – these methods: setMonthlyFee, the accessor getMonthlyFee, the mutator applyMonthlyFee, which charges the monthly fee to the account 38