Inheritance Phil Tayco San Jose City College Slide version 1.2

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
OBJECT ORIENTED PROGRAMMING M Taimoor Khan
CMSC 202 Inheritance. Aug 6, Object Relationships An object can have another object as one of instance variables. The Person class had two Date.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
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,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
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.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
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.
Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
The Object-Oriented Thought Process Chapter 03
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Phil Tayco Slide version 1.0 Created Sep 18, 2017
Inheritance ITI1121 Nour El Kadri.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Inheritance and Polymorphism
Phil Tayco Slide version 1.0 Created Nov 6, 2017
Phil Tayco Slide version 1.1 Created Oct 30, 2017
Chapter 5 Hierarchies IS-A associations superclasses subclasses
An Introduction to Inheritance
Phil Tayco Slide version 1.0 Created Nov. 26, 2017
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Comparing Objects Phil Tayco San Jose City College Slide version 1.1
Chapter 9 Inheritance and Polymorphism
Composition Phil Tayco San Jose City College Slide version 1.2
Phil Tayco Slide version 1.0 Created Oct 2, 2017
Phil Tayco Slide version 1.0 Created Oct 16, 2017
Inheritance Basics Programming with Inheritance
Comp 249 Programming Methodology
Inheritance I Class Reuse with Inheritance
Chapter 9 Object-Oriented Programming: Inheritance
Java Programming Language
Phil Tayco Slide version 1.0 Created Oct 9, 2017
Lecture 22 Inheritance Richard Gesick.
Polymorphism Phil Tayco San Jose City College Slide version 1.1
Week 6 Object-Oriented Programming (2): Polymorphism
CMSC 202 Inheritance.
Java Programming Arrays
Java Programming Loops
Fundamental Error Handling
Class Reuse with Inheritance
Java Programming Function Introduction
Computer Programming with JAVA
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
Fundaments of Game Design
Object Comparisons and Arrays
Object-Oriented Programming
Java Programming Loops
Review of Previous Lesson
Review of Previous Lesson
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Java Programming Function Introduction
CS 240 – Advanced Programming Concepts
Phil Tayco San Jose City College Slide version 1.2 Updated Sep 9, 2019
Presentation transcript:

Inheritance Phil Tayco San Jose City College Slide version 1.2 Updated Oct. 14, 2018

Current Concepts We can create custom complex data types known as classes with instances of them called objects Classes are designed to be stand-alone and reused as much as possible Classes contain properties and behaviors (what a class has and what capabilities it can provide) Certain behaviors are suggested with all classes (constructors, set/get, equals, toString) Composition is designing classes with properties with data types defined using other classes Structures like arrays that use data types can similarly be applied with classes (e.g. array of Alarms or Students) We now look at another type of relationship between classes

Back to Student public class Student { private int id; private String name; private Date dateOfBirth; At this point, methods for supporting these properties should be straightforward Other properties could be added to Student as desired Existing properties can be changed (id as a String, name as a new class Name) What about different types of Students? A high school Student attends a school and has a GPA A college Student attends a school, has a GPA and a major An elementary Student attends a school and has a grade

Back to Student A common initial thought is to add all the properties in these examples and add a type property: public class Student { private int id; private String name; private Date dateOfBirth; private String school; private double gpa; private int grade; private String major; private char studentType; What do you think are the implications with coding methods with this approach?

Irrelevant Properties A good example of the impact of this design is seen with constructors public Student (int i, String n, Date d, int g, String s) { id = i; name = n; dateOfBirth = new Date(d); school = s; grade = g; studentType = ‘E’; gpa = 0; major = “”; }

Irrelevant Properties This constructor is for an elementary school student object The properties that are relevant to this object are sent in The constructor hard codes the studentType (shouldn’t be set from the functional call) Other properties are set with values that will not be needed This leads to arguments for this approach Perhaps these properties could be used later The stringType property could be used by main to determine the type of student through code if (s.getStringType() == ‘E’)…

Irrelevant Properties Following this pattern for a high school Student: public Student (int i, String n, Date d, int gr, String s, double g) { id = i; name = n; dateOfBirth = new Date(d); school = s; grade = gr; studentType = ‘H’; gpa = g; major = “”; }

Irrelevant Properties This looks like a normal overloaded constructor The properties specific to the high school student are managed appropriately The property specific to a college student is set with no value (same as with elementary student) Other properties are set the same as with the previous constructor The pattern for this design approach makes sense and leads to the next question What if we don’t need these specific properties or only want to define a basic student?

Irrelevant Properties public Student (int i, String n, Date d, String s) { id = i; name = n; dateOfBirth = new Date(d); school = s; grade = “”; studentType = ‘’; gpa = 0.0; major = “”; }

Irrelevant Properties The input parameters in these examples represent defining different types of Students They are distinguished by another property relying on the data values assigned What about the other methods? These examples suggest that there are methods that would also become irrelevant based on the type of the actual Student object created getMajor() would not be needed for high school student setGpa(3.5) would not be needed for elementary The equals method may take advantage of the use of the stringType or depend on the idea that irrelevant properties will have empty values The most notable impact of this approach is with the toString method

Irrelevant Properties public String toString() { String result = “”; result += String.format(“%d: %s born on %s attends %s”, id, name, dateOfBirth, school); This first part works is addresses the properties considered to be part of all Students After this, it may make sense to only show other property values based on the studentType value If we didn’t do this, then this method would have to show all property values that may be blank 123: Phil Tayco born on 01/01/1990 attends “school” with GPA of 0.0 majoring in “” in grade 0.

Irrelevant Properties public String toString() { String result = “”; result += String.format(“%d: %s born on %s attends %s”, id, name, dateOfBirth, school); switch(studentType) case ‘E’: result += String.format(“ in grade %d”, grade); break; case ‘H’: result += String.format(“ has GPA %.2f”, gpa); …

Irrelevant Properties This may seem like a clever piece of code to handle the different types of Student objects Before OOP, data types driven by values was how code was managed It is still effective and can be done, but the arguments against it show clear benefits particularly as requirements change and new types are introduced In this data driven approach, the Student class takes on much responsibility and has to know the different types of Students that can be created To learn how to address this with an OO approach, we can look at these examples to define characteristics (properties) of the different types of Students

Student Types When we look at what a Student “has” for properties, we get the following from these examples: All Students have an ID, name, date of birth and school Elementary Students have the same properties of a Student and also have a grade High School Students have the same properties of a Student and also have a GPA College Students have the same properties of a Student and also have a GPA and a major College Students could also be seen as having the same properties of High School Students with just the addition of a major…) If we took this design and applied what we know so far, we would develop 4 classes as follows

Student Types public class Student { private int id; private String name; private Date dateOfBirth; private String school; } public class ElementaryStudent private int grade;

Student Types public class HighSchoolStudent { private int id; private String name; private Date dateOfBirth; private String school; private double gpa; } public class CollegeStudent private String major;

Student Types Notice the similarities between these classes – all share id, name, date of birth, and school Notice also the differences: ElementaryStudents also have a grade HighSchoolStudents also have a gpa CollegeStudents also have a gpa and major Set/get, constructors, equals, and toString methods can easily be derived individually with each class Notice that for properties that are common between classes, code for those specific properties are likely to be the same If we examine the similar properties in these classes, they are all defined in the Student class

Student Types Conceptually, this accurately represents the properties of all Students (that we have decided to model) Subsequently, the other class definitions happen to have the same property design as Student plus an attribute or two These attributes are conceptually relevant to the specific class (elementary students have grades, high school and college students have GPAs, and college students have majors) Some of these specific attributes are also same (high school and college students have GPAs) Most important is that they are defined in the specific class – the definition and methods used will be relevant to and owned by that class This also means other classes don’t know nor have to define those methods

Student Types The Student class itself is just like any other class and Student objects can be instantiated Set/get, constructors, equals, and toString methods are still defined as normal For Student, the methods will be defined relevant to Student properties and behaviors Because the Student class properties appear in all classes defined, it implies a class structure with potential for code reuse In OO languages like Java, we can define ElementaryStudent and reuse Student

Student Types public class ElementaryStudent extends Student { private int grade; } Here, an ElementaryStudent has all the properties and functions defined in Student In addition, it defines its own grade In this design, ElementaryStudent is considered to be a “subclass” of a the more general Student Subclasses “inherit” the design of the parent/super class Subclass code is simplified to focus on code specific to the characteristics of that subclass HighSchoolStudent is similarly defined

Student Types public class HighSchoolStudent extends Student { private double gpa; } HighSchoolStudent inherits from Student and adds its own gpa property HighSchoolStudent and ElementaryStudent are separate classes – they just happen to have the same parent class CollegeStudent can also inherit from Student and define gpa and major within it accordingly However, CollegeStudent also has the same definition of gpa as in HighSchoolStudent so we could reuse from there instead, if we want

Student Types public class CollegeStudent extends HighSchoolStudent { private String major; } CollegeStudent now has the same properties as HighSchoolStudent Since HighSchoolStudent inherits the properties of Student, the CollegeStudent class indirectly inherits its properties too Most important is the awareness of these classes within this structure The Student class is designed without any knowledge that HighSchool and College will inherit from it College is designed inheriting from HighSchool without any knowledge that HighSchool inherited from Student The lack of knowledge makes for more relevant coding within the specific classes – classes only need to code with what they specifically contain

Inheritance Hierarchy Graphically, classes using inheritance are usually depicted as follows The arrows pointing up signify subclasses inheriting from super/parent classes and parent/child type of relationship The subclasses are considered to be “types of” superclasses (i.e. a HighSchoolStudent “is a type of” Student) Student Elementary HighSchool College

Inheritance Hierarchy Notice that in real life, a college student is not a type of high school student! This emphasizes that the relationship between classes is from a class property perspective When we say CollegeStudent is a type of HighSchoolStudent, we mean CollegeStudent has the same properties as a HighSchool student, plus more As one goes up the inheritance hierarchy, classes higher up are conceptually more “general” while classes going down are conceptually more “specialized”

Inheritance Hierarchy Adding the properties of the classes to the picture shows where definitions are owned and reused What about grade level for high school and college? Student int id String name Date dateOfBirth String school ElementaryStudent int grade HighSchoolStudent double gpa CollegeStudent String major

Inheritance getId is defined in the parent class Student public class Student { public int getId() return id; } getId is defined in the parent class Student An object created as a Student can use this function as normal Because classes like ElementaryStudent inherit from Student, those objects can also use it Subclasses do not need to redefine inherited methods (though there may be situations when redefining such a function is necessary…)

Inheritance public static void main(String[] args) { Student s = new Student(); HighSchoolStudent h = new HighSchoolStudent(); CollegeStudent c = new CollegeStudent(); System.out.println(s.getId()); System.out.println(h.getId()); System.out.println(c.getId()); } Main doesn’t even know this reuse of code through inheritance is even happening, nor should it!

Constructors A subclass will not be able to access properties in the superclass if they are private (more on that later) Conceptually, we think of subclasses “having” the properties it inherits from the superclass As such, we tend to want to constructor code in the subclass to do the same thing public ElementaryStudent(int i, String n, Date d, String s, int g) { id = i; name = n; dateOfBirth = new Date(d); school = s; grade = g; }

Constructors However, 4 of these properties are defined in Student and they are marked as private Because they are private, direct access to them is not allowed, and the rule still applies even with subclasses using inheritance To fix this, Java allows you to call the parent class constructor directly from the subclass public ElementaryStudent(int i, String n, Date d, String s, int g) { super(i, n, d, s); grade = g; }

Constructors “super” calls the parent constructor with the matching signature (in this case, the Student constructor that takes an int, String, Date, and another String) In Java, “super” must be the first line in the subclass constructor Other OO languages will offer a similar functionality Using “super” promotes reuse of code and proper ownership of behavior Elementary is first saying use how ever Student constructs an object from these parameters Then, Elementary initializes the properties it specifically knows about – in this case, the grade property Alternatively, there can be ways to allow the subclass to access superclass properties directly

Private Access public class Student { protected int id; protected String name; protected Date dateOfBirth; protected String school; } Protected properties are considered private for other objects and code outside the class Protected properties can be directly accessed only within subclasses of its inheritance hierarchy Pure OO designers mark properties as private as often to promote stand alone class design and not need to know how it will specifically be used If a class is likely to have subclasses, protecting properties can be helpful

Overriding Methods Reusing methods is a primary benefit to using inheritance with classes and subclasses In many situations, though, methods in subclasses may want to redefine the inherited method functionality For example, suppose high school students are passing with a GPA of at least 2.0 public boolean isPassing() { return (gpa >= 2.0); }

Overriding Methods Because CollegeStudent inherits from HighSchoolStudent, the isPassing method defined there will be reused However, suppose college students are considered passing with at least a GPA of 3.0? public boolean isPassing() { return (gpa >= 3.0); } This is the exact same function signature as the one defined in HighSchoolStudent - yet, this will not generate a compile error

Overriding Methods Methods in subclasses can “override” methods in the superclass when they have matching signatures Method overrides allow a subclass to redefine functionality specific to its class even when the method is inherited from the super class Notice that this is not a form of method overloading (because overloading would mean the input parameters would be different) Overriding is often utilized with inheritance and necessary to understand for advanced topics in OOP (see “polymorphism” later)

Overriding Methods Java also allows for a special notation with overrides: @Override public boolean isPassing() { return (gpa >= 3.0); } The @Override statement explicitly states that the method is overriding a method from the parent class. This is considered good practice: The compiler ensures the method is overriding a matching signature from the parent. This helps make sure your code is written as intended The code is more readable by specifically calling out that an override is occurring

Inheritance Summary Class design is intended to model real world scenarios and promote code reuse, maintenance and readability Class relationships and similarities between them generate opportunities for code reuse Classes individually are designed by identifying their properties and behaviors – what does it have and what do we want it to be able to do Classes collectively can define relationships through identifying if one class is a type of another The higher level class contains the common properties and methods that all subclass types can reuse and are considered to be a more general type of information Subclasses add on to these types defining more specific properties data and add/override methods Objects of super and subclasses are instantiated as normal, sometimes not even aware that inheritance is in use In addition to straight code reuse, the inheritance hierarchy also sets up the foundation for a more powerful use of super and subclasses

Exercise 5 At this point, you have a considerable amount of classes designed and coded from your exercises A Block contains up to 20 Houses (array practice) A House contains an Address and other properties (composition practice) An Address contains a ZipCode and other properties (more composition practice) For first practicing inheritance, design 2 classes that are special types of a House A DesignerHouse is a House designed by a person by name and adds some dollar amount to the house value A CommercialHouse is a House that has some kind of commercial business Business’ have a name and a standard annual profit – the calculation of profit within a Business will be defined some time later (standard annual profit for now as a fixed amount defined when a Business instance is created)

Exercise 5 Add to the House class a property for value and a method for calculating expected value House expected values are simply the value of the House itself DesignerHouse values are the house value plus the value of the designer CommercialHouse values are the house value plus whatever standard annual profit it has Your methods for calculating expected value per class should use inheritance and method overriding appropriately Keep your original test functionality from previous exercises – when you add testing code for the new classes, your previous code should not be changed