1 / 38

Inheritance

Learn how to create custom student classes with inheritance and handle properties and behaviors specific to different types of students.

Download Presentation

Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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

  3. 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

  4. 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?

  5. 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 = “”; }

  6. 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’)…

  7. 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 = “”; }

  8. 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?

  9. 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 = “”; }

  10. 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

  11. 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.

  12. 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); break; …

  13. 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

  14. 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

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

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

  17. 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

  18. 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

  19. 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

  20. Student Types public class ElementaryStudentextends 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

  21. 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

  22. 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

  23. 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

  24. 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”

  25. 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 • HighSchoolStudent • double gpa • ElementaryStudent • int grade • CollegeStudent • String major

  26. Inheritance 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…)

  27. 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!

  28. 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; }

  29. 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; }

  30. 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

  31. Private Access public class Student { protectedint 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

  32. 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 booleanisPassing() { return (gpa >= 2.0); }

  33. 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 booleanisPassing() { 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

  34. 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)

  35. Overriding Methods Java also allows for a special notation with overrides: @Override public booleanisPassing() { 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

  36. 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

  37. 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)

  38. 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

More Related