Module 3 Part 1 Inheritance 9112021 CSE 1321










































- Slides: 42
Module 3 - Part 1 Inheritance 9/11/2021 CSE 1321 Module 2 1
2 Introduction • Inheritance allows a new class to “absorb” an existing class’s members. • Inheritance saves time by reusing proven and debugged high-quality software. • Best shown through an example 4/26/2018 6 -2
An Example – Mammal Class • What do all mammals have? • • Mammal Temperature Weight Intelligence level Fur color - temp - weight - i. Q - fur. Color • What do all mammals do? • • Eat( ) Drink( ) Move( ) Give. Birth( ) + Eat( ) + Drink( ) + Move( ) + Give. Birth( ) • So far, no inheritance This is called a UML Diagram 9/11/2021 CSE 1321 Module 4 3
The Dog Class • What we could do is just copy/paste the code and rename to Dog Mammal Dog - temp - weight - i. Q - fur. Color • Do the same thing for: • • Cat Elephant Boar Cow + Eat( ) + Drink( ) + Move( ) + Give. Birth( ) • No copy/pasting! BAD! USE INHERITANCE when classes are similar 9/11/2021 CSE 1321 Module 4 4
Inheritance Mammal - temp - weight - i. Q - fur. Color + Eat( ) + Drink( ) + Move( ) + Give. Birth( ) Dog Cat Cow Note: arrows point up to class they inherit from 9/11/2021 CSE 1321 Module 4 5
Inheritance • Trick questions: • how many attributes does Dog have? • how many methods does Dog have? 9/11/2021 CSE 1321 Module 4 6
Inheritance • Trick questions: • how many attributes does Dog have? • how many methods does Dog have? • Dog, Cat, and Cow have 4 attributes and 4 methods, even though you can’t see them • No need to redeclare those attributes • It’s because of inheritance! 9/11/2021 CSE 1321 Module 4 7
Customizing your Dog • Your Dog is basically no different than a Mammal • At this point, you can: • Add additional attributes • Add additional methods • You can also override (redefine) inherited methods • Don’t confuse overriding with overloading (which is having two methods with the same name) 9/11/2021 CSE 1321 Module 4 8
9 Terminology • The is-a relationship represents inheritance. • a Dog is a Mammal • a Cow is a Mammal • Mammal is called a base class, a super class, or a parent class (all mean the same thing) • Dog/Cow/Cat would be a derived class, a sub class, or child class 4/26/2018 6 -9
What it looks like in C# using System; class Mammal { public float weight; public int i. Q; } class Dog : Mammal { // There are 2 attributes here that you // can't see because of inheritance! } class Main { public static void Main (string[] args) { Dog d = new Dog(); } } 9/11/2021 CSE 1321 Module 4 10
What it looks like in Java import java. util. *; class Mammal { public float weight; public int i. Q; } class Dog extends Mammal { // There are 2 attributes here that you // can't see because of inheritance! } class Main { public static void main (String[] args) { Dog d = new Dog(); } } 9/11/2021 CSE 1321 Module 4 11
Inheritance Fundamentals • The hierarchy can be extended: Mammal Dog Labrador • A Labrador is-a Dog • A Labrador is-a Mammal • A Mammal has-a string (fur. Color) 9/11/2021 CSE 1321 Module 4 12
Thought-Provoking Concept #1 (abstract classes) • Is there such a thing as a Mammal? • Not really… so we’d never create one in code! // Doesn’t make sense Mammal m = new Mammal (); • Because we never want people to create a Mammal like above, you mark the class as abstract • We’ll talk about this later 9/11/2021 CSE 1321 Module 4 13
Thought-Provoking Concept #2 (polymorphism) • When assigning values, the data type on the right side must match the data type on the left side: int i = 17; // types match, so we’re good • Similar questions: • • 9/11/2021 Is a Dog? Yes. Is a Cat? Yes. Is a Dog a Mammal? Is a Mammal a Dog? CSE 1321 Module 4 14
Thought-Provoking Concept #2 (polymorphism) • Are these assignments legal? 1. Dog d = new Dog( ); 2. Cat c = new Cat( ); 3. Mammal m = new Dog( ); // m is now a Dog 4. m = new Cat( ); // Wow! m just became a cat! • Lines 3 and 4 demonstrate polymorphism, where a variable (m) is changing types while the program is running • In line 3, m behaves like a Dog • In line 4, m behaves like a Cat • We’ll talk about it later, but this is the #1 job interview question. 9/11/2021 CSE 1321 Module 4 15
End Intro. Let’s get into details. 9/11/2021 CSE 1321 Module 4 16
Lesson #1 – Object is the mother of all classes • All classes inherit from Object • If you don’t specify, a class directly inherits from Object • This will be “invisible” code • Object defines basic things like to. String( ) • You need to override to. String( ) • Redefine it to print something meaningful • When overriding, method signature must match • Default: print memory address of object (Java) or class name (C#) 9/11/2021 CSE 1321 Module 4 17
Example of “Invisible Code” - Java // This class. . . class Mammal { public float weight; public int i. Q; } //. . . is exactly the same thing as this one class Mammal extends Object { public float weight; public int i. Q; } 9/11/2021 CSE 1321 Module 4 18
Example of “Invisible Code” – C# // This class. . . class Mammal { public float weight; public int i. Q; } //. . . is exactly the same thing as this one class Mammal : Object { public float weight; public int i. Q; } 9/11/2021 CSE 1321 Module 4 19
Example of Overriding To. String() – C# class Mammal : Object { public float weight; public int i. Q; public Mammal () { weight = 7; i. Q = 45; } } class Dog : Mammal { public override string To. String() { // C# requires the keyword override string s = "Weight is ” + weight; s+= " and IQ is ” + i. Q + "n"; return s; } } class Main { public static void Main (string[] args) { Dog d = new Dog(); Console. Write. Line(d); // Weight is 7 and IQ is 45 } } 9/11/2021 CSE 1321 Module 4 20
Example of Overriding To. String() – Java class Mammal extends Object { public float weight; public int i. Q; public Mammal () { weight = 7; i. Q = 45; } } class Dog extends Mammal { public String to. String() { // There’s an optional @Override in Java String s = "Weight is " + weight; s+= " and IQ is " + i. Q + "n"; return s; } } class Main { public static void main(String[] args) { Dog d = new Dog(); System. out. println(d); // Weight is 7 and IQ is 45 } } // @Override tells the compiler to check the // override is correct. See book for example. 9/11/2021 CSE 1321 Module 4 21
22 Methods of Object – C# Method Description Equals(Object) Determines whether the specified object is equal to the current object. Equals(Object, Object) Determines whether the specified object instances are considered equal. Finalize() Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. Get. Hash. Code() Get. Type() Memberwise. Clone() Reference. Equals(Object, Object) Serves as the default hash function. Gets the Type of the current instance. Creates a shallow copy of the current Object. Determines whether the specified Object instances are the same instance. To. String() Returns a string that represents the current object. 4/26/2018 6 -22
23 Methods of Object - Java Method Description clone() Creates and returns a copy of this object. equals(Object obj) Indicates whether some other object is "equal to" this one. get. Class() Returns the runtime class of this Object. hash. Code() Returns a hash code value for the object. notify() Wakes up a single thread that is waiting on this object's monitor. notify. All() Wakes up all threads that are waiting on this object's monitor. to. String() Returns a string representation of the object. wait() Causes the current thread to wait until another thread invokes the notify() method or the notify. All() method for this object. wait(long timeout) Causes the current thread to wait until either another thread invokes the notify() method or the notify. All() method for this object, or a specified amount of time has elapsed. wait(long timeout, int nanos) Causes the current thread to wait until another thread invokes the notify() method or the notify. All() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed. 4/26/2018 6 -23
Lesson #2 – Multiple Inheritance not allowed (except in C++) Man Wolf - weight - num puppies + run( ) Werewolf w = new Werewolf( ); w. run(); // which run method is called? 9/11/2021 CSE 1321 Module 4 24
Note about interfaces Man Wolf - weight - num puppies + run( ) Werewolf - weight - num puppies + run( ) Keep this example in mind. We’ll revisit it when talking about interfaces later. 9/11/2021 CSE 1321 Module 4 25
Lesson #3 - Referencing Parent Classes Before understanding this concept, you have to understand the keyword this Let’s review 9/11/2021 CSE 1321 Module 4 26
Understanding this class Phone { String manufacturer; float version; Phone(String manufacturer, float version) { this. manufacturer = manufacturer; // Use this to reference class this. version = version; // members, or this. initialize(); // call methods within the class } Phone() { this("Nokia", 1. 337 f); // Use this to call another constructor } void initialize( ) { } // Code to initialize the Phone } class Main { public static void main(String[] args) { Phone p = new Phone(); } } 9/11/2021 CSE 1321 Module 4 27
Lesson #3 - Referencing Parent Classes • super and base are how we reference things in the parent class • super – Java • base – C# • In the child classes, you may see code like: • super. my. Method( ) – call the parent class’s my. Method() • base. my. Method( ) – C#’s way of doing it • Best shown through examples 9/11/2021 CSE 1321 Module 4 28
Example: Referencing Parent Classes - Java class Mammal extends Object { public void make. Noise() { System. out. println ("AHOOWOOW"); } } class Dog extends Mammal { @Override public void make. Noise() { super. make. Noise(); System. out. println("Woof!"); } } class Main { public static void main(String[] args) { Dog d = new Dog(); d. make. Noise(); // Prints AHOOWOOW then Woof! } } 9/11/2021 CSE 1321 Module 4 29
Example: Referencing Parent Classes – C# class Mammal : Object { // C# folks! If you want the child class to be // able to override, you must mark it as virtual public virtual void Make. Noise() { Console. Write. Line("AHOOWOOW"); } } class Dog : Mammal { public override void Make. Noise() { base. Make. Noise(); Console. Write. Line("Woof!"); } } class Example { public static void Main (string[] args) { Dog d = new Dog(); d. Make. Noise(); } } 9/11/2021 CSE 1321 Module 4 30
Lesson #3 - Referencing Parent Classes • When you see super() or base() directly called: • It’s calling the parent constructor • This happens whether you like it or not!!! • This is more “invisible code” • Best shown through examples 9/11/2021 CSE 1321 Module 4 31
This code is exactly like… class Mammal { public Mammal() { Console. Write. Line("Mammal constructor"); } } class Dog : Mammal { public Dog() { Console. Write. Line("Dog constructor"); } } class Example { public static void Main (string[] args) { // Wow! Output is: // Mammal constructor // Dog constructor Dog d = new Dog(); } } 9/11/2021 CSE 1321 Module 4 32
… this code – C# class Mammal : Object { public Mammal() { Console. Write. Line("Mammal constructor"); } } class Dog : Mammal { public Dog() : base() { // Note how we call Mammal’s constructor Console. Write. Line("Dog constructor"); } } class Example { public static void Main (string[] args) { // Wow! Output is: // Mammal constructor // Dog constructor Dog d = new Dog(); } } 9/11/2021 CSE 1321 Module 4 33
And this code… class Mammal { public Mammal () { System. out. println ("Mammal constructor"); } } class Dog extends Mammal { public Dog() { System. out. println("Dog constructor"); } } class Main { public static void main(String[] args) { // Wow! Output is: // Mammal constructor // Dog constructor Dog d = new Dog(); } } 9/11/2021 CSE 1321 Module 4 34
… is exactly like this code - Java class Mammal extends Object { public Mammal () { System. out. println ("Mammal constructor"); } } class Dog extends Mammal { public Dog() { super(); System. out. println("Dog constructor"); } } class Main { public static void main(String[] args) { // Wow! Output is: // Mammal constructor // Dog constructor Dog d = new Dog(); } } 9/11/2021 CSE 1321 Module 4 35
Lesson #4 – Access Modifiers • There are four levels of visibility (for this course) • Here are loose/sloppy definitions: • • public – is visible everywhere in the code private – is visible only within the class protected – is visible only within the class or child classes default – varies by language • In general, visible to class in the same package/namespace • Note: you do not specify ‘default’ in your code • Note: default is a keyword used in switch statements 9/11/2021 CSE 1321 Module 4 36
37 Access Modifiers in Inheritance Access Modifiers Access Location public protected default private Same Class Yes Yes Sub-Class of the Same Package Yes Yes NO Another Class of the Yes Same Package Yes NO Sub-Class of Another Yes Package Yes NO NO Sub-Class/ Class of Another Package No NO NO Yes Figure: Base Class Member’s Visibility Modes 4/26/2018 6 -37
38 Lesson #4 – Access Modifiers • There are language specific rules associated with each modifier, so reference the book! • private members are not inherited and are not directly accessible by child-class methods and properties. • 4/26/2018 Must access a parent’s private variables by methods of that parent class 6 -38
Example: private variables - Java class Mammal { private int body. Temp; // only Mammal can see this public int get. Temp() {return body. Temp; } // Accessor protected void change. Temp(int new. Temp) { // Modifier body. Temp = new. Temp; } } class Dog extends Mammal { // Dog doesn't have access to body. Temp, so use Mammal's accessor public void change. Temp(int new. Temp) { super. change. Temp(new. Temp); } } class Main { public static void main (String[] args) { Dog d = new Dog(); d. change. Temp(99); // Correct way System. out. println(d. get. Temp()); // 99 d. body. Temp = 95; // Doesn't compile } } 9/11/2021 CSE 1321 Module 4 39
Example: private variables – C# class Mammal { private int body. Temp; // only Mammal can see this public int get. Temp() {return body. Temp; } // Accessor protected void change. Temp(int new. Temp) { // Modifier body. Temp = new. Temp; } } class Dog : Mammal { // Dog doesn't have access to body. Temp, so use Mammal's accessor public void change. Temp(int new. Temp) { base. change. Temp(new. Temp); } } class Main { public static void Main (string[] args) { Dog d = new Dog(); d. change. Temp(99); // Correct way Console. Write. Line(d. get. Temp()); // 99 d. body. Temp = 95; // Doesn't compile } } 9/11/2021 CSE 1321 Module 4 40
41 Odds and Ends • Declaring instance variables as private and providing getters/setters helps enforce good design • A change in a parent class propagates down to child classes – good for maintenence/design • Constructors are not inherited. Why not? • Class Object’s default (empty) constructor does nothing, but will always be called. 4/26/2018 6 -41
Summary • Inheritance • One class “absorbs” members from another class • Doesn’t absorb constructors or private members • You can only inherit from one class • You can access parent methods/variables using super or base • Access modifiers change what’s inherited and what is visible 9/11/2021 CSE 1321 Module 2 42