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. 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 3 Introduction Inheritance allows a new class to absorb an existing class’s members. A derived class normally adds its own fields 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 class BaseClass { // BaseClass Members } // end of base class
4 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 4/26/2018 4

5 Inheritance Block Diagram
5 Inheritance Concept class Result extends Student{ //Inheriting Student class private float Mark; protected void setMark(); public void display(); } class Student{ private int Roll; protected String Name; public void setData(); } 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; 4/26/2018 5

6 6 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. In Java, the class hierarchy begins with the class Object. 4/26/2018 6

7 All java classes inherit directly or indirectly from Object
7 Java Class Object All java classes inherit directly or indirectly from Object Figure: java.lang package’s classes 4/26/2018 7

8 Levels of Introduction
8 Levels of Introduction Java does not support Multiple Inheritance; But C++ does 4/26/2018 8

9 Introduction 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 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 10

11 Base Classes and Derived Classes
11 Base Classes and Derived Classes The UML class diagram shows an inheritance hierarchy representing a university community. Each arrow represents an is-a relationship. 4/26/2018 11

12 Base Classes and Derived Classes
12 Base Classes and Derived Classes Now consider the Shape inheritance hierarchy. We can follow the arrows to identify several is-a relationships. 4/26/2018 12

13 Base Classes and Derived Classes
13 Base Classes and Derived Classes Objects of all classes that extend a common base class can be treated as objects of that base class. However, base-class objects cannot be treated as objects of their derived classes. When a derived class needs a customized version of an inherited method, the derived class can override the base-class method. 4/26/2018 13

14 private and protected members
14  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 14

15 private and protected members
15 private and protected members Properties and methods of a derived class cannot directly access private members of the base class. A derived class can change the state of private base-class fields only through non-private methods and properties provided in the base class. If a derived class can access its base class’s private fields, classes that inherit from that base class could access the fields as well. This would propagate access to what should be private fields, and the benefits of information hiding would be lost. 4/26/2018 15

16 Access Modifiers in Inheritance
16 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 No Figure: Base Class Member’s Visibility Modes 4/26/2018 16

17 Private Members Cannot be Inherited
17 Private Members Cannot be Inherited Private Members are accessed through their setters and getters 4/26/2018 17

18 C# Base Classes and Derived Classes
18 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. The compiler sets the base class of a class to object when the class declaration does not explicitly extend a base class. 4/26/2018 18

19 Java Base Classes and Derived Classes
19 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. The compiler sets the base class of a class to object when the class declaration does not explicitly extend a base class. 4/26/2018 19

20 Base Classes and Derived Classes
20 Base Classes and Derived Classes Declaring instance variables as private and providing public properties and/or methods to manipulate and validate them helps enforce good design. Constructors are not inherited. Either explicitly or implicitly, a call to the base-class constructor is made. Class object’s default (empty) constructor does nothing. Note that even if a class does not have constructors, the default constructor will call the base class’s default or parameterless constructor. 4/26/2018 20

21 A Quick Review on toString() Method
21 A Quick Review on toString() Method The toString() returns a string representing an object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method. What happens if the Derived class does /does not override the toString()? No issue for primitive data types But it affects for Class and Reference Types 4/26/2018 21

22 22 C# ToString ToString is special - it is one of the methods that every class inherits directly or indirectly from class object. Method ToString returns a string representing an object. object’s ToString method is primarily a placeholder that typically should be overridden by a derived class. 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. 4/26/2018 22

23 23 C# ToString ToString is special - it is one of the methods that every class inherits directly or indirectly from class object. Method ToString returns a string representing an object. object’s ToString method is primarily a placeholder that typically should be overridden by a derived class. 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. 4/26/2018 23

24 24 Java toString toString is special - it is one of the methods that every class inherits directly or indirectly from class Object. Method toString returns a string representing an object. Object’s toString method is primarily a placeholder that typically should be overridden by a derived class. To override a base-class method, a derived class must declare a method with the same signature as the base class method. @Override is optional but it forces the compiler to check that the override is correct @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. 4/26/2018 24

25 More on toString() Method
25 More on toString() Method The toString() returns a string representing an object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method. What happens if the Derived class does /does not override the toString()? No issue for primitive data types But it affects for Class and Reference Types 4/26/2018 25

26 More on toString() Method
26 More on toString() Method Not needed/allowed for primitive data types But it affects for Class and Reference Types package methodOverriding; public class Overriding_toString { public static void main(String[] args) { int x = 101; System.out.println("x = " + x); // System.out.println("x = " + x.toString); // Invalid use of toString() Integer y = 202; System.out.println("y = " + y); System.out.println("y.toString() = " + y.toString()); } Output: x = 101 y = 202 y.toString() = 202 4/26/2018 26

27 More on toString() Method
27 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 27

28 More on toString() Method
28 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 28

29 More on toString() Method
29 More on toString() Method Calling the Calling toString() with argument package methodOverriding; public class Calling_toString_Overriding { public static void main(String[] args) { int x = 101; System.out.println("x = " + x); Integer y = 202; System.out.println("y = " + y); System.out.println("y.toString() = " + y.toString()); // Calling toString() with argument System.out.println("(12).toString() = " + Integer.toString(12)); System.out.println("(12.5).toString() = " + Double.toString(12.5)); } Output: x = 101 y = 202 y.toString() = 202 (12).toString() = 12 (12.5).toString() = 12.5 4/26/2018 29

30 Base Classes and Derived Classes
30 Base Classes and Derived Classes 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 30

31 Base Classes and Derived Classes
31 Base Classes and Derived Classes Copying and pasting code from one class to another can spread errors across multiple source-code files. Use inheritance rather than the “copy-and-paste” approach. With inheritance, the common members of all the classes in the hierarchy are declared in a base class. When changes are required for these common features, you need to make the changes only in the base class—derived classes then inherit the changes. 4/26/2018 31

32 Base Classes and Derived Classes
32 Base Classes and Derived Classes A compilation error occurs if a derived-class constructor calls one of its base-class constructors with arguments that do not match the number and types of parameters specified in one of the base-class constructor declarations. 4/26/2018 32

33 C# Base Classes and Derived Classes
33 C# Base Classes and Derived Classes The virtual and abstract keywords indicate that a base- class method can be overridden in derived classes. A subclasses may override a virtual method but it must override an abstract method. The override modifier declares that a derived-class method overrides a virtual or abstract base-class method. This modifier also implicitly declares the derived-class method virtual. A subclass may not override methods that are not marked as abstract, virtual or override 4/26/2018 33

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

35 Base Classes and Derived Classes
35 Base Classes and Derived Classes Using protected instance variables creates several potential problems. The derived-class object can set an inherited variable’s value directly without validity checking. Derived-class methods would need to be written to 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 35

36 Base Classes and Derived Classes
36 Base Classes and Derived Classes When a base/super-class method is overridden in a derived class, the derived-class version often calls the base/super-class version to do a portion of the work. Failure to prefix the base/super-class method name with the keyword base when referencing the base class’s method causes the derived-class method to call itself. 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 36

37 Constructors in Derived Classes
37  Constructors in Derived Classes The derived-class constructor, before performing its own tasks, invokes its direct base class’s constructor. This is done either explicitly or implicitly. If the base class is derived from another class, the base-class constructor invokes the constructor of the next class up in the hierarchy, and so on. 4/26/2018 37

38 Constructors in Derived Classes
38 Constructors in Derived Classes When an application creates a derived-class object, the derived-class constructor calls the base-class constructor (explicitly, via base, or implicitly). The base-class constructor’s body executes to initialize the base class’s instance variables that are part of the derived-class object, then the derived class constructor’s body executes to initialize the derived-class-only instance variables. Even if a constructor does not assign a value to an instance variable, the variable is still initialized to its default value. 4/26/2018 38

39 Programming with Inheritance
39 Programming with Inheritance • When a new class extends an existing class, the new class inherits the members of the existing class. • We can customize the new class to meet our needs by including additional members and by overriding base-class members. • 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 39

40 Programming with Inheritance
40 Programming with Inheritance Although inheriting from a class does not require access to the class’s source code, developers often insist on seeing the source code to understand how the class is implemented. They may, for example, want to ensure that they are extending a class that performs well and is implemented securely. Effective software reuse greatly improves the software-development process. Object-oriented programming facilitates software reuse. The availability of class libraries delivers the maximum benefits of software reuse. 4/26/2018 40

41 Programming with Inheritance
41 Programming with Inheritance At the design stage in an object-oriented system, the designer often finds that certain classes are closely related. The designer should “factor out” common members and place them in a base class. Declaring a derived class does not affect its base class’s source code. Inheritance preserves the in­tegrity of the base class. 4/26/2018 41

42 Programming with Inheritance
42 Programming with Inheritance Designers of object-oriented systems should avoid class proliferation. Such proliferation creates management problems and can hinder software reusability, because in a huge class library it becomes difficult for a client to locate the most appropriate classes. If derived classes are larger than they need to be (i.e., contain too much functionality), memory and pro­cessing resources might be wasted. Extend the base class containing the functionality that is closest to what is needed. 4/26/2018 42

43 All classes inherit directly or indirectly from object.
43 C# Class object All classes inherit directly or indirectly 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 43

44 All java classes inherit directly or indirectly from Object
44 Java Class Object All java classes inherit directly or indirectly 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 44

45 All java classes inherit directly or indirectly from Object
45 Java Class Object All java classes inherit directly or indirectly from Object Figure: java.lang package’s classes 4/26/2018 45

46 All java classes inherit directly or indirectly from Object
46 Java Class Object All java classes inherit directly or indirectly 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 46


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

Similar presentations


Ads by Google