Docsity

Extending Classes and Inheritance - Object Oriented and GUI Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Extending Classes and Inheritance - Object Oriented and GUI Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

1

Chapter 6: Extending classes and

Inheritance

2

Basics of Inheritance

  • One of the basic objectives of Inheritance is code reuse
  • If you want to extend the functionality of an old class, you do not need to reinvent the wheel. All what you need is to inherit from that class and add the new features you want to introduce.
  • The original class is called super, base or parent class while the new one is called derived or child class.
  • When you create an object of the derived class it always contain a complete object of the parent one with all its data members and methods in addition to its own stuff.

4

Basics of Inheritance (Cont.)

  • If you define a member or a method in the

child class with the same exact name as

the one in the parent THEN the derived

class name will override (hide) the parent

class one

  • Overriding the base class method
  • Ex: “TestDerived2”
  • Inheritance also allows us to apply a

principal called Polymorphism

5

Polymorphism

  • The ability of a single variable of a given type to reference objects of other types
  • Advantages: Among others, the ability to change program behavior at run time
  • To polymorphically call a method, it must be defined in both the base and the derived class
  • Also, the object type needs to be of the parent class but the stored object can be any of its children or grandchildren
  • Ex: “TryPolymorphism”
  • You can inherit from a child class and this can continue deeper and deeper to create an inheritance tree
  • Ex: “TryPolymorphism2”

7

Universal Superclass

  • The Object class is the root for all classes

in Java. (check its methods)

  • We can determine the type of an object

using the getClass() method of Object

which returns an object of type Class and

the getName() method of Class.

  • To execute a method unique to a

particular class you need to explicitly cast

down the inheritance hierarchy.

  • Ex: “LayEggs”

8

Casting & interfaces

  • To identify the type of an object stored in a parent class member, you can use the instanceof operator
  • In case you create an inheritance hierarchy just to take advantage of polymorphic calls, you might define the parent class as an Interface
  • To take the concept of abstract classes one step farther, Java provides a way to make every method abstract by creating an interface instead of a class.
  • An Interfaces does not define what a method does rather it just defines its form