00:00

Understanding Inheritance in Object-Oriented Programming

Inheritance in programming allows a new class to inherit properties and behaviors from an existing class, promoting code reusability and efficient design. This concept is illustrated through Unified Modeling Language (UML) diagrams, emphasizing the relationship between base and derived classes. Key points include the use of abstract classes, polymorphism, and the foundational role of the Object class in Java and C#.

bautis
Download Presentation

Understanding Inheritance in Object-Oriented Programming

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. Module 3 - Part 1 Inheritance

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

  3. UML - Unified Modeling Language • Often you’ll need to discuss design of classes with coworkers. Being able to visualize your classes in a consistent way is very helpful. • UML allows you to draw the important details of a class for discussion. • Most IDEs have built in way to draw a UML diagram from your code. Typically teams have an up to date UML on their wall near their work area, so they can quickly reference Methods/Attributes for classes. • Each class is drawn as a rectangle, with the class name at the top, followed by all the attributes, then all the methods. • Constructors are often not mentioned.

  4. UML permissions ● Attributes and methods that are public will have a + on front of them. ● Attributes and methods that are private will have a - on front of them. ● Later we’ll learn about protected, it’s represented by a #

  5. An Example – Mammal Class • What do all mammals have? • Temperature • Weight • Intelligence level • Fur color • What do all mammals do? • Eat( ) • Drink( ) • Move( ) • GiveBirth( ) • So far, no inheritance Mammal + temp + weight + iQ + furColor + Eat( ) + Drink( ) + Move( ) + GiveBirth( ) This is called a UML Diagram

  6. The Dog Class • What we could do is just copy/paste the code and rename to Dog Mammal Dog + temp + weight + iQ + furColor • Do the same thing for: • Cat • Elephant • Boar • Cow + Eat( ) + Drink( ) + Move( ) + GiveBirth( ) • No copy/pasting! BAD! USE INHERITANCE when classes are similar

  7. Inheritance Mammal + temp + weight + iQ + furColor + Eat( ) + Drink( ) + Move( ) + GiveBirth( ) Cat Cow Dog Note: arrows point up to class they inherit from

  8. Inheritance •Trick questions: • how many attributes does Dog have? • how many methods does Dog have?

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

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

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

  12. What it looks like in C# using System; class Mammal { public float weight; public int iQ; } 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(); } }

  13. What it looks like in Java import java.util.*; class Mammal { public float weight; public int iQ; } 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(); } }

  14. 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 (furColor)

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

  16. 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: • Is a Dog a Dog? Yes. • Is a Cat a Cat? Yes. • Is a Dog a Mammal? • Is a Mammal a Dog?

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

  18. 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 toString( ) • You need to override toString( ) • Redefine it to print something meaningful • When overriding, method signature must match • Default: print memory address of object (Java) or class name (C#)

  19. Example of “Invisible Code” in Java // This class... class Mammal { public float weight; public int iQ; } // ...is exactly the same thing as this one class Mammal extends Object { public float weight; public int iQ; }

  20. Example of “Invisible Code” in C# // This class... class Mammal { public float weight; public int iQ; } // ...is exactly the same thing as this one class Mammal : Object { public float weight; public int iQ; }

  21. Example of Overriding ToString() – C# class Mammal : Object { public float weight; public int iQ; public Mammal () { weight = 7; iQ = 45; } } class Dog : Mammal { public override string ToString() { // C# requires the keyword override string s = "Weight is ” + weight; s+= " and IQ is ” + iQ + "\n"; return s; } } class Main { public static void Main (string[] args) { Dog d = new Dog(); Console.WriteLine(d); // Weight is 7 and IQ is 45 } }

  22. Example of Overriding ToString() – Java class Mammal extends Object { public float weight; public int iQ; public Mammal () { weight = 7; iQ = 45; } } class Dog extends Mammal { @Override public String toString() { String s = "Weight is " + weight; s+= " and IQ is " + iQ + "\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

  23. Methods of Object – C# Method Equals(Object) Description 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. GetHashCode() GetType() MemberwiseClone() ReferenceEquals(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. ToString() Returns a string that represents the current object.

  24. Methods of Object - Java Method clone() Creates and returns a copy of this object. Description equals​(Object obj) Indicates whether some other object is "equal to" this one. getClass​() Returns the runtime class of this Object. hashCode​() Returns a hash code value for the object. notify​() Wakes up a single thread that is waiting on this object's monitor. notifyAll​() Wakes up all threads that are waiting on this object's monitor. toString​() Returns a string representation of the object. wait​() Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. wait​(long timeout) Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() 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 notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

  25. Multiple Inheritance not allowed Man Wolf - weight - num puppies + run( ) + run( ) Werewolf - weight - num puppies + run( ) Werewolf w = new Werewolf( ); w.run(); // which run method is called?

  26. Note about interfaces Man Wolf - weight - num puppies + run( ) + run( ) Werewolf - weight - num puppies + run( ) Keep this example in mind. We’ll revisit it when talking about interfaces later.

  27. super and base keywords •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.myMethod( ) – call the parent class’s myMethod() • base.myMethod( ) – C#’s way of doing it • Best shown through examples

  28. Example: Referencing Parent Classes - Java class Mammal extends Object { public void makeNoise() { System.out.println ("AHOOWOOW"); } } class Dog extends Mammal { @Override public void makeNoise() { super.makeNoise(); System.out.println("Woof!"); } } class Main { public static void main(String[] args) { Dog d = new Dog(); d.makeNoise(); // Prints AHOOWOOW then Woof! } }

  29. 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 MakeNoise() { Console.WriteLine("AHOOWOOW"); } } class Dog : Mammal { public override void MakeNoise() { base.MakeNoise(); Console.WriteLine("Woof!"); } } class Example { public static void Main (string[] args) { Dog d = new Dog(); d.MakeNoise(); } }

  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

  31. This code is exactly like… class Mammal { public Mammal() { Console.WriteLine("Mammal constructor"); } } class Dog : Mammal { public Dog() { Console.WriteLine("Dog constructor"); } } class Example { public static void Main (string[] args) { // Wow! Output is: // Mammal constructor // Dog constructor Dog d = new Dog(); } }

  32. … this code – C# class Mammal : Object { public Mammal() { Console.WriteLine("Mammal constructor"); } } class Dog : Mammal { public Dog() : base() { // Note how we call Mammal’s constructor Console.WriteLine("Dog constructor"); } } class Example { public static void Main (string[] args) { // Wow! Output is: // Mammal constructor // Dog constructor Dog d = new Dog(); } }

  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(); } }

  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(); } }

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

  36. 36 Access Modifiers in Inheritance Access Modifiers Access Location public protected default private Same Class Yes Yes Yes Yes Sub-Class of the Same Package Yes Yes Yes NO Another Class of the Same Package Yes Yes Yes NO Sub-Class of Another Package Yes Yes NO NO Sub-Class/ Class of Another Package Yes No NO NO Figure: Base Class Member’s Visibility Modes

  37. 37 Lesson #4 – Access Modifiers There are language specific rules associated with each modifier. • C#: Most things are private by default • Java: Most things are public by default • private members are not inherited and are not directly accessible by child-class methods and properties. Must access a parent’s private variables by methods of that parent class • •

  38. Example: private variables - Java class Mammal { private int bodyTemp; // only Mammal can see this public int getTemp() {return bodyTemp;} protected void changeTemp(int newTemp) { // Modifier bodyTemp = newTemp; } } class Dog extends Mammal { // Dog doesn't have access to bodyTemp, so use Mammal's accessor public void changeTemp(int newTemp) { super.changeTemp(newTemp); } } class Main { public static void main (String[] args) { Dog d = new Dog(); d.changeTemp(99); // Correct way System.out.println(d.getTemp()); // 99 d.bodyTemp = 95; // Doesn't compile } } // Accessor

  39. Example: private variables – C# class Mammal { private int bodyTemp; // only Mammal can see this public int getTemp() {return bodyTemp;} protected void changeTemp(int newTemp) { // Modifier bodyTemp = newTemp; } } class Dog : Mammal { // Dog doesn't have access to bodyTemp, so use Mammal's accessor public void changeTemp(int newTemp) { base.changeTemp(newTemp); } } class Main { public static void Main (string[] args) { Dog d = new Dog(); d.changeTemp(99); // Correct way Console.WriteLine(d.getTemp()); // 99 d.bodyTemp = 95; // Doesn't compile } } // Accessor

  40. 40 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 maintenance/design • Constructors are not inherited. Why not? • Class Object’s default (empty) constructor does nothing, but will always be called.

  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

More Related