Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 6 Inheritance CSE 1322 4/26/2018.

Similar presentations


Presentation on theme: "Lecture 6 Inheritance CSE 1322 4/26/2018."— Presentation transcript:

1 Lecture 6 Inheritance CSE 1322 4/26/2018

2 OBJECTIVES How inheritance promotes software reusability.
2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To create a derived class that inherits attributes and behaviors from a base class. To use access modifier protected to give derived-class methods access to base-class members. To access base-class members with base. Or super. How constructors are used in inheritance hierarchies. The methods of class object, the direct or indirect base class of all classes. 4/26/2018 2

3 Introduction – Main Idea
3 Introduction – Main Idea Inheritance allows a class to absorb an existing class’s members. Terminology: base/derived (C#, C++) super/sub (Java) parent/child (generic terms) A derived class normally adds more attributes and methods to represent a more specialized group of objects. Inheritance saves time by reusing proven and debugged high-quality software. 4/26/2018 3

4 Introduction – Powerful!
4 Introduction – Powerful! Copying/pasting code from one class to another can spread errors. Instead, use inheritance. When designing classes, push all the common ”stuff” up into a base class. Benefit? A simple change to the base class propagates all the way down the class hierarchy! 4/26/2018 4

5 class BaseClass { // BaseClass Members } // end of base class
5 Inheritance Concept class BaseClass { // BaseClass Members } // end of base class Java Syntax class DerivedClass extends BaseClass { // DerivedClass own Members } // end of derived class C# Syntax class DerivedClass : BaseClass { // DerivedClass own Members } // end of derived class Note! The direction of the arrows matters and is often wrong! 4/26/2018 5

6 Inheritance Block Diagram
6 Inheritance Concept class Student { private int Roll; protected String Name; public void setData(); } class Result extends Student { //Inheriting from Student private float Mark; protected void setMark(); public void display(); } Result Class private Section float Mark; protected Section void setMarks(); public Section void display(); void setData(); Inherited from Student Class Inheritance Block Diagram String Name; Question: how many attributes does Result have? Answer: 3! It inherited 2. 4/26/2018 6

7 7 Introduction The direct base class is the base class which the derived class explicitly inherits. An indirect base class is any class above the direct base class in the class hierarchy. In C# the class hierarchy begins with class object. All classes inherit from it! In Java, the class hierarchy begins with the class Object. All classes inherit from it! 4/26/2018 7

8 8  Examples The figure lists several simple examples of base classes and derived classes. Note that base classes are “more general,” and derived classes are “more specific.” 4/26/2018 8

9 The is-a relationship represents inheritance.
9 Introduction The is-a relationship represents inheritance. For example, a car is a vehicle, and a truck is a vehicle. New classes can inherit from thousands of pre-built classes in class libraries. 4/26/2018 9

10 Base Classes and Derived Classes
10 Base Classes and Derived Classes The UML class diagram shows an inheritance hierarchy representing a university community. Each arrow represents an is-a relationship. Animal Mammal Reptile Dog Platypus Lizard Professor A Lizard is a reptile which is an Animal 4/26/2018 10

11 11 Multiple Inheritance Is it possible to inherit from more than one class? class Man { int IQ; void walk(); void wasteTime(); } class Wolf { int ; void walk(); void howl(); } class Werewolf { // Inherited stuff } 4/26/2018 11

12 Multiple Inheritance C++ allows for multiple inheritance
Java and C# do not allow multiple inheritance. Why? What happens when you call the following code: Werewolf w1 = new Werewolf(); w1.walk(); Does w1 walk like a man or a wolf? 4/26/2018

13 private and protected members
13  private and protected members A base class’s private members are inherited by derived classes, but are not directly accessible by derived-class methods and properties. A base class’s protected members can be accessed by members of that base class and by members of its derived classes. C# A base class’s protected internal members can be accessed by members of a base class, the derived classes and by any class in the same assembly. 4/26/2018 13

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

15 C# Base Classes and Derived Classes
15 C# Base Classes and Derived Classes A colon (:) followed by a class name at the end of the class declaration header indicates that the class extends the class to the right of the colon. public class Student : Person Every class directly or indirectly inherits object’s methods. If a class does not specify that it inherits from another class, it implicitly inherits from object. 4/26/2018 15

16 Java Base Classes and Derived Classes
16 Java Base Classes and Derived Classes The key word extends followed a class name at the end of the class declaration header indicates that the class extends the class to the right of the word extends. public class Student extends Person Every class directly or indirectly inherits Object’s methods. If a class does not specify that it inherits from another class, it implicitly inherits from Object. 4/26/2018 16

17 17 Things to Note Constructors are not inherited and we still have default constructors Class object’s default (empty) constructor does nothing. Either explicitly or implicitly, a call to the base-class constructor is made. Can’t call a base constructor with arguments that do not match the number and types of parameters. Note that even if a class does not have constructors, the default constructor will call the base class’s default or parameterless constructor. Let’s see an example 4/26/2018 17

18 Example of “invisible code”
class MyObject extends Object { MyObject() { super(); } } // Same thing as ↑ class MyObject { } class MyObject : object { MyObject() { base(); } } // Same thing as ↑ class MyObject { } 4/26/2018

19 class Base { // Example in Java Base() { System. out
class Base { // Example in Java Base() { System.out.println("Base Constructor"); } } class Child extends Base { Child() { // super call is here, but you can't see it! System.out.println ("Child constructor"); class Main { public static void main(String[] args) { Child c = new Child(); // Output: Base Constructor Child Constructor 4/26/2018

20 A Quick Review of toString() Method
20 A Quick Review of toString() Method We include toString() in a class to return a string representing an object. Can’t call toString() on a primitive variable (e.g. int, float..) It is recommended that all subclasses override this method. Question: What happens if the Derived/sub class doesn’t override toString()? 4/26/2018 20

21 C# ToString() Is designed to be overridden!
21 C# ToString() ToString() is special - it is one of the methods that every class inherits directly or indirectly from class object. This returns a string representing an object. Is designed to be overridden! To override a base-class method, a derived class must declare a method with keyword override. public override string ToString() { } The method must have the same signature (method name, number of parameters and parameter types) and return type as the base-class method. Base method must be marked virtual (can be overridden) Note: virtual and override go together like PB&J 4/26/2018 21

22 Java toString() Same as C#, however…
22 Java toString() Same as C#, however… @Override is optional but it forces the compiler to check that the override is correct @Override public String ToString() { } Can make a method “non-overridable” using the final keyword 4/26/2018 22

23 More on toString() Method
23 More on toString() Method The toString() returns a string representing an object. What happens if the Derived class does not override the toString()? package methodOverriding; public class MyFriend { String name; String ; MyFriend (String name, String ) { this.name = name; this. = ; } // Without Overriding the toString() Method public static void main(String[] args) { MyFriend f1 = new MyFriend("John", System.out.println(f1); // System.out.println(f1.toString()); // Output: 4/26/2018 23

24 More on toString() Method
24 More on toString() Method What happens if we override the toString()? package methodOverriding; public class MyFriend { String name; String ; MyFriend (String name, String ) { this.name = name; this. = ; } @Override public String toString() // With Overriding the toString() Method { return "My friend: "+ name + “\t" + ; } public static void main(String[] args) { MyFriend f1 = new MyFriend("John", System.out.println(f1); // System.out.println(f1.toString()); // Output: My friend: John 4/26/2018 24

25 public class MyFriend { string name, ; public MyFriend(string name, string ) { this.name = name; this. = ; } public override string ToString() { return "My friend: "+name+"\t"+ ; } class MainClass { public static void Main (string[] args) { Console.WriteLine(new MyFriend("Bob", Output: My friend: Bob 4/26/2018

26 Rules about Overriding
26 Rules about Overriding It is a compilation error to override a method with a different access modifier. If a public method could be overridden as a protected or private method, the derived-class objects would not respond to the same method calls as base-class objects. 4/26/2018 26

27 C# Base Classes and Derived Classes
27 C# Base Classes and Derived Classes virtual indicates that a base-class method can be overridden in derived classes. It may/not do that. There’s another keyword (abstract) that requires a method to be overridden. Later. A subclass may not override methods that are not marked as abstract, virtual or override 4/26/2018 27

28 Java Base Classes and Derived Classes
28 Java Base Classes and Derived Classes Similarly, the abstract keyword indicate that a base-class method must be overridden in derived classes. 4/26/2018 28

29 Problems with Protected
29 Problems with Protected Using protected instance variables creates several potential problems. The derived-class can set an inherited variable’s value directly without validity checking. Derived-class methods depend on the base class’s data implementation. You should be able to change the base-class implementation while still providing the same services to the derived classes. Declaring base-class instance variables private enables the base-class implementation of these instance variables to change without affecting derived-class implementations. 4/26/2018 29

30 Calls to a Base Class’s methods
30 Calls to a Base Class’s methods When a base/super-class method is overridden, the derived-class version often calls the base/super-class version to do a portion of the work. Use either base or super to call those methods The use of “chained” base references to refer to a member several levels up the hierarchy—as in base.base.Earnings() or super.super.Earnings()—is a compilation error. 4/26/2018 30

31 class Base { void doSomething(){ System. out
class Base { void doSomething(){ System.out.println("Base doSomething"); } } class Child extends Base { void doSomething() { super.doSomething(); System.out.println("Child doSomething"); class Main { public static void main(String[] args) { Child c = new Child(); c.doSomething(); Output: Base doSomething Child doSomething 4/26/2018

32 class Base { public virtual void doSomething(){ Console
class Base { public virtual void doSomething(){ Console.WriteLine("Base doSomething"); } } class Child : Base { public override void doSomething() { base.doSomething(); Console.WriteLine("Child doSomething"); class MainClass { public static void Main (string[] args) { Child c = new Child(); c.doSomething(); Output: Base doSomething Child doSomething 4/26/2018

33 33 Commercially Independent software vendors (ISVs) can develop and sell proprietary classes. • Users then can derive new classes from these library classes without accessing the source code. 4/26/2018 33

34 Inherited Methods from object
34 Inherited Methods from object 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. GetHashCode() Serves as the default hash function. GetType() Gets the Type of the current instance. MemberwiseClone() Creates a shallow copy of the current Object. ReferenceEquals(Object, Object) Determines whether the specified Object instances are the same instance. ToString() Returns a string that represents the current object. 4/26/2018 34

35 Inherited Methods from Object
35 Inherited Methods from Object Method Description clone​() Creates and returns a copy of this object. 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. 4/26/2018 35


Download ppt "Lecture 6 Inheritance CSE 1322 4/26/2018."

Similar presentations


Ads by Google