inheritance l.
Skip this Video
Loading SlideShow in 5 Seconds..
Inheritance PowerPoint Presentation
Download Presentation

Loading in 2 Seconds...

play fullscreen
1 / 73

Inheritance - PowerPoint PPT Presentation

  • Uploaded on

Inheritance. Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse We will focus on: deriving new classes creating class hierarchies the protected modifier polymorphism via inheritance

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Inheritance' - paul

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
  • Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse
  • We will focus on:
    • deriving new classes
    • creating class hierarchies
    • the protected modifier
    • polymorphism via inheritance
    • inheritance used in graphical user interfaces
the three pillars of oop
The Three Pillars of OOP
  • The Three Pillars of OOP
  • Encapsulation
  • Inheritance
  • Polymorphism
  • Every class in Java extends some other class. If you don't explicitly specify the class that your new class extends, it will automatically extend the class named Object.
class hierarchy
Class Hierarchy
  • Java uses a class hierarchy to organize its classes.
  • Thus, all classes in Java exist in a class hierarchy where the class named Object forms the root of the hierarchy.
  • Some classes extend Object directly, while other classes are subclasses of Object further down the hierarchy.
  • Inheritance allows a software developer to derive a new class from an existing one
  • The existing class is called the parent class, or superclass, or base class
  • The derived class is called the child class or subclass.
  • As the name implies, the child inherits characteristics of the parent.
  • That is, the child class inherits the methods and data defined for the parent class
  • This means that you can write the code for one class and have all its child classes have access to it.



  • Inheritance relationships are shown in a UML class diagram using a solid arrow with an unfilled triangular arrowhead pointing to the parent class
  • Proper inheritance creates an is-a relationship, meaning the child is a more specific version of the parent
  • A subclass inheritsstate and behavior.
  • Recall that an object’s state is reflected in the form of instance variables and its behavior in the form of methods.
  • The child inherits both from all of its ancestors.
  • Child classes can use the items inherited from its parent or super class as is, or the child class can modify or override the methods of the parent class.
  • This means that the child class can contain a method with the same name as the parent class.
  • A programmer can tailor a derived class as needed by adding new variables or methods, or by modifying the inherited ones
  • Software reuse is a fundamental benefit of inheritance
  • By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software
child classes
Child Classes
  • The method in the child class deals with the behavior that is particular to the child class.
  • We have a class SHAPE and SHAPE has a child class RECTANGLE and a child class TRIANGLE.
  • The SHAPE class will contain methods that are common to both child classes, e.g. and Area() method
  • Both child classes will have a method that calculates its Area.
  • Only the formulas for each Area calculation will differ.
  • This leads to smaller and easier to understand systems.
  • Using inheritance, common descriptions can be reused, promoting the concept of code reusability.
  • A child class can have a method with the same name as the parent class only its method implements what it is capable of doing.
  • Inheritance cuts redundancy as descendant classes only implement the extra information that differentiates them from the parent class
  • When changes are made on the common information, all child classes automatically inherit it.
  • Thus the models that are created are easier to modify and implement.
  • In Java, the reserved wordextends is used to establish an inheritance relationship
sub or child classes
Sub or Child Classes
  • To declare a subclass you would write:

class subclass extends SuperClass { . . . } or,

class Dictionary extends Book{…}

  • A Java class can have only one direct superclass.
  • Member variables defined in the subclass hide member variables of the same name in the superclass. Consider this superclass and subclass pair:
sub or child classes14
Sub or Child Classes

class Super {

protected int num;

public Super(int anum){

num = anum;


class Sub extends Super {

float num1;

public Sub(int newnum, float Fnum) {


num1 = Fnum;


deriving subclasses
Deriving Subclasses
  • In Java, we use the reserved word extends to establish an inheritance relationship

class Car extends Vehicle


// class contents


  • See
  • See
  • See
controlling inheritance
Controlling Inheritance
  • Visibility modifiers determine which class members get inherited and which do not
  • Variables and methods declared with public visibility are inherited, and those with private visibility are not
  • But public variables violate our goal of encapsulation
  • There is a third visibility modifier that helps in inheritance situations: protected
the protected modifier
The protected Modifier
  • The protected visibility modifier allows a member of a base class to be inherited into the child
  • The protected visibility modifier provides more encapsulation than public does.
  • Encapsulation requires that we protect as much as possible out instance variables from outside accesss.
  • The details of each modifier are given in Appendix F
the protected modifier18
The protectedModifier
  • The visibility modifiers determine which class members get inherited and which do not.
  • Variables and methods declared with public visibility are inherited, and those with private visibility are not.
  • But public variables violate our goal of encapsulation.
  • The protectedvisibility modifier allows a member to be inherited, but provides more protection than publicdoes.
the super reference
The super Reference
  • Constructors are not inherited, even though they have public visibility
  • Yet we often want to use the parent's constructor to set up the "parent's part" of the object
  • The super reference can be used to refer to the parent class, and is often used to invoke the parent's constructor
  • See (page 328)
  • See (page 329)
  • See (page 330)
class diagram for words
Class Diagram for Words


# pages : int

+ pageMessage() : void



- definitions : int

+ main (args : String[]) : void

+ definitionMessage() : void

the super reference21
The Super Reference
  • The super reference can be used to refer to the parent class, and is often used to invoke the parent's constructor.
  • In, The Dictionary class uses the super reference to call the parent constructor so that the number of pages can be set.
  • If it did not call the parent constructor, it would have to initialize the number of pages in its own constructor. Let us look at
super reference
Super Reference
  • When we create the constructor for a child class, we should invoke the constructor for the superclass also.
  • To do this, the first line of our constructor should contain the keyword super followed by a parameter list as though calling a method named super().
  • The parameter list must match the parameters in the argument list of the superclass constructor.e.g.

super(num_pages) // initializes the # of pages

super reference23
Super Reference
  • This causes the constructor for the superclass to be invoked using parameters passed from the subclass.
  • Thus memory is allocated for all the data in the super class. The child class now has full access to it.
  • The Dictionary class invokes the parent class constructor with: super(num_pages)
  • Since the Dictionary class inherits the variable pages from the parent class Book, it has to initialize this variable in its constructor.
  • But the parent class constructor already does this initialization.
  • Since constructors are not inherited, the Dictionary sub class can use the superreference to invoke the parent class constructor.
the super reference25
The Super Reference
  • A child object inherits the allowable fields and methods of its parent . The one duty of the default constructor is to support this.
  • Each instance of a child class inherits the specified methods and variables of the parent class. So the parent class’s instance variables must be properly initialized.
inheritance and constructors
Inheritance and Constructors
  • Every constructor has 3 tasks to perform:

1. Instantiate the parent object and initialize its


2. Initialize any fields local to its class

3. perform the statements in the constructor

  • If you do not call the parent constructor with super when the super class constructor has parameters, then the instance variables in the parent class will not be initialized.
defined vs inherited
Defined vs. Inherited
  • A subtle feature of inheritance is the fact that even if a method or variable is not inherited by a child, it is still defined for that child.
  • An inherited member can be referenced directly in the child class, as if it were declared in the child class
  • But even members that are not inherited exist for the child, and can be referenced indirectly through parent methods
  • In Eating.Java, a pizza object is created that can access private methods and variables in the parent class.
overriding methods
Overriding Methods
  • A child class canoverride the definition of an inherited method in favor of its own.
  • This is different from the overloading that we used in Constructors.
  • That is, a child can redefine a method it inherits from its parent.
  • The new method must have the same signature as the parent's method, but can have different code in the body
overriding methods29
Overriding Methods
  • See
  • See
  • See
  • Note that a parent method can be explicitly invoked using the super reference
overloading vs overriding
Overloading vs. Overriding
  • Don't confuse the concepts of overloading and overriding
  • Overloading deals with multiple methods in the same class with the same name but different signatures
  • Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature
  • Overloading lets you define a similar operation in different ways for different data
  • Overriding lets you define a similar operation in different ways for different object types
overriding methods31
Overriding Methods
  • A subclass can either completely override an inherited method, or the subclass can enhance it.
  • The subclass can use the keyword super to invoke the version in the superclass.
  • For instance, if have a method called deposit() in the child class and a method called deposit() in the parent class, the child class would call the parent method with:


  • The object type determines which method is invoked.

Savings_Account s = new Savings_Account(“Tom”);

Account b = new Account(“Bob”);

s.deposit(25.00); // defined in Savings_Accountb.deposit(25.00);// method defined in Account class

  • Don't confuse the concepts of overloading and overriding
overriding methods33
Overriding Methods
  • To overload a method, you must duplicate the method name, but use a different argument list.
  • To overridea method, you must match the entire method signature.
  • If you aren't careful when writing your new method signature, you will be overloading methods when you think that you are overriding them.
  • This is a situation where you don't get any warnings from the JDK compiler.
  • If a method is declared with the final modifier, it cannot be overridden
  • The concept of overriding can be applied to data and is called shadowing variables
  • Shadowing variables should be avoided because it tends to cause unnecessarily confusing code
the super reference revisited
The super Reference Revisited
  • A method in the parent class can be invoked explicitly using the super reference
  • The super reference can be used to invoke any method from the parent class.
  • This ability is often helpful when using overridden methods
  • The syntax is:



  • When we extend an existing class, we 'inherit' all of the attributes, and methods, of the parent class.
  • In the program, the child class can deposit, and withdraw - even though we only explicitly define a new method for withdrawal.
  • This makes programming much easier, and simpler, as we don't re-invent the wheel each time we extend other classes.
  • In the example above, we add two new methods , and call the constructor of our parent class.
class hierarchies
Class Hierarchies
  • Two children of the same parent are called siblings.
  • Good class design puts all common features as high in the hierarchy as is reasonable.
  • Class hierarchies often have to be extended and modified to keep up with changing needs
  • There is no single class hierarchy that is appropriate for all situations
single vs multiple inheritance
Single vs. Multiple Inheritance
  • Java supports single inheritance, meaning that a derived class can have only one parent class
  • Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents
  • Collisions, such as the same variable name in two parents, have to be resolved
  • In most cases, the use of interfaces gives us the best aspects of multiple inheritance without the overhead
class hierarchies39
Class Hierarchies







  • A child class of one parent can be the parent of another child, forming class hierarchies
the object class
The Object Class
  • A class called Object is defined in the java.lang package of the Java standard class library
  • All classes are derived from the Object class
  • If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class
  • The Object class is therefore the ultimate root of all class hierarchies
the object class41
The Object Class
  • The Object class contains a few useful methods, which are inherited by all classes
  • For example, the toString method is defined in the Object class
  • Every time we have defined toString, we have actually been overriding it
  • The toString method in the Object class is defined to return a string that contains the name of the object’s class and a hash value

Class Object

  • The class Object defines the following methods:
    • clone()
    • equals(Object obj)
    • finalize()
    • getClass()
    • hashCode()
    • notify()
    • notifyAll()
    • toString()
    • wait()
    • wait(long timeout)
    • wait(long timeout, int nanos) 
  • As you can see, this list includes three overloaded versions of the method named wait (same name, different formal argument lists).
class object
Class Object
  • Because every class is either a direct or indirect subclass of Object, every class in Java, (including new classes that you define), inherit these eleven methods.
  • Generally speaking, many of these eleven methods are intended to be overridden for various purposes.
  • However, some of them, such as getClass, notify, and wait, are intended to be used directly without overriding.
the object class44
The Object Class
  • That’s why the println method can call toString for any object that is passed to it – all objects are guaranteed to have a toString method via inheritance
  • See


  • See
  • The equals method of the Object class determines if two references are aliases
  • You may choose to override equals to define equality in some other way
references and inheritance
References and Inheritance
  • Assigning a predecessor object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment
  • Assigning an ancestor object to a predecessor reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast
  • The widening conversion is the most useful
  • What is polymorphism?
  • The meaning of the word polymorphism is something like one name, many forms.
  • How does Java implement polymorphism?
  • Polymorphism manifests itself in Java in the form of multiple methods having the same name.
  • In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods).
  • In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).

Three distinct forms of polymorphism

  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface
polymorphism via inheritance
Polymorphism via Inheritance
  • A polymorphic reference is one which can refer to different types of objects at different times.
  • Inheritance can also be used as a basis of polymorphism
  • An object reference can refer to one object at one time, then it can be changed to refer to another object (related by inheritance) at another time
polymorphism via inheritance49
Polymorphism via Inheritance
  • Suppose the Holiday class has a method called celebrate, and the Christmas class overrode it
  • Now consider the following invocation:


  • If day refers to a Holiday object, it invokes the Holiday version of celebrate; if it refers to a Christmas object, it invokes the Christmas version

Accounts[] customer= new Accounts[10];

Senior_Savings Sam = new Senior_Savings(“Sam”);

customer[5] = Sam;

Accounts Ricky = new Accounts(“Ricky”);

customer[3] = Ricky;

So the array customer of class Accounts holds both Senior-Savings and regular Accounts.

  • The Senior_Savings class overrides the Account class methoddeposit with a deposit method of its own.
  • We assign a position in the customer accounts array (which is an array of Customer accounts) to a Senior_Savings account.
  • So the customer holds both regular customer accounts and Senior_Savings accounts.
  • The deposit method that is called depends on what type of object is in the array.
class bank
Class Bank

public class Bank


public static void main(String args[]) {

  Account [] customer = new Account[10];

for (int i=0; i< 3; i++) {

System.out.print ("Name of customer:);

String name =;

System.out.print ("Type of Account: S for Senior, R for regular ");

  String type =;

  acctype = type.charAt(0);

if(acctype == 'S'){

customer[i] = new Senior_Savings(Name, acctype, accountnumber++); } else if (acctype == 'R’)

customer[i] = new Account(Name, acctype, accountnumber++);

 } // close for

class account
Class Account
  • When we call the deposit method in a loop , the deposit method that is called depends on whether the object in the array is of the Account class or the Senior_Savings class.

if(acctype == 'S')

{ customer[i] = new SeniorSavings(name, acctype, accnum++);

customer[i].deposit(45); } else if (acctype == 'R’)


customer [i] = new Account(name, acctype, acctnum++);

customer[i].deposit(75); }

  • In general, it is the type of the object being referenced determines which method is invoked.
  • Objects of Thought class and Advice class are instantiated. They both contain a method called message.
  • Initially, they each call their respective methods. Then the Thought object is assigned the value of the advice object.
  • When the message method is invoked by the Thoughtobject, the advice version is executed.
  • Note that, if an invocation is in a loop, the exact same line of code could execute different methods at different times.
  • Polymorphic references are therefore resolved at run-time, not during compilation
  • Note that, because all classes inherit from the Objectclass, an Object reference can refer to any type of object .
  • A ArrayList is designed to store Object references of any type.
  • The instanceOf operator can be used to determine the class from which an object was created
variety java
Variety. java

public static void main (String[] args) {

// create a vector called collector

ArrayList collector = new ArrayLIst();

// create an integer object num1

Integer num1 = new Integer (10);


// create an point object, origin

  Point origin = new Point (0, 0);


// create an integer object and store it in the vector

Integer num2 = new Integer (37);

collector.add (num2);

variety program
Variety Program
  • int temp;

  Object someObject;

for (int count=0; count < 4; count++) {

  someObject = collector.elementAt (count);

if (someObject instanceof Integer) {

temp = ((Integer)someObject).intValue() + 20;

System.out.println (something + " + 20 = " + temp);

} else

System.out.println ("Point: " + something);


} // method main

variety java59
  • In the Variety program, while iterating through a loop different objects as assigned to an object which is defined as;

someObject = collector.elementAt(count);

if (someObject.instanceof Integer){

  • Polymorphism means that the sender of a message does not need to to be aware of which class the receiving object belongs to.
  • The receiving instance can belong to an any class
  • A sender object needs only to know that another object can perform a certain behavior, not which class it belongs to nor which operations will perform that behavior.
  • Flexible systems can thus be implemented.
  • When a new object from a new class is added, this modification should only affect this new object not those who send messages to it
indirect access
Indirect Access
  • An inherited member can be referenced directly by name in the child class, as if it were declared in the child class
  • But even if a method or variable is not inherited by a child, it can still be accessed indirectly through parent methods
  • See (page 355)
  • See (page 356)
  • See (page 357)
final methods
Final Methods
  • A final method cannot be overridden.
  • Declaring a method final prevents the derived class from erroneously redefining a class method.
  • Declaring a method final allows the compiler to perform inline optimization.
  • final classes cannot be extended.
abstract classes
Abstract Classes
  • An abstract class is a placeholder in a class hierarchy that represents a generic concept
  • An abstract class cannot be instantiated
  • We use the modifier abstract on the class header to declare a class as abstract
  • An abstract class often contains abstract methods (like an interface does), though it doesn’t have to
abstract classes64
Abstract Classes
  • An abstract class is a placeholder in a class hierarchy that represents a generic concept
  • An abstract class cannot be instantiated
  • We use the modifier abstract on the class header to declare a class as abstract:

public abstract class Product


// contents


abstract classes65
Abstract Classes
  • An abstract class often contains abstract methods with no definitions (like an interface)
  • Unlike an interface, the abstract modifier must be applied to each abstract method
  • Also, an abstract class typically contains non-abstract methods with full definitions
  • A class declared as abstract does not have to contain abstract methods -- simply declaring it as abstract makes it so
abstract classes66
Abstract Classes
  • The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract
  • An abstract method cannot be defined as final or static
  • The use of abstract classes is an important element of software design – it allows us to establish common elements in a hierarchy that are too generic to instantiate
interface hierarchies
Interface Hierarchies
  • Inheritance can be applied to interfaces as well as classes
  • That is, one interface can be derived from another interface
  • The child interface inherits all abstract methods of the parent
  • A class implementing the child interface must define all methods from both the ancestor and child interfaces
  • Note that class hierarchies and interface hierarchies are distinct (they do not overlap)
abstract classes68
Abstract Classes
  • The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract
  • An abstract method cannot be defined as final (because it must be overridden) or static (because it has no definition yet)
  • The use of abstract classes is a design decision; it helps us establish common elements in a class that is to general to instantiate
applets and inheritance
Applets and Inheritance
  • An applet is an excellent example of inheritance
  • Recall that when we define an applet, we extend the Applet class
  • The Applet class already handles all the details about applet creation and execution, including the interaction with a web browser
  • Our applet classes only have to deal with issues that specifically relate to what our particular applet will do
extending event adapter classes
Extending Event Adapter Classes
  • The creation of listener classes is done by implementing a particular interface (such as MouseListener interface)
  • A listener can also be created by extending a special adapter class of the Java class library
  • Each listener interface has a corresponding adapter class (such as the MouseAdapter class)
  • Each adapter class implements the corresponding listener and provides empty method definitions
extending event adapter classes71
Extending Event Adapter Classes
  • When you derive a listener class from an adapter class, you override any event methods of interest (such as the mouseClicked method)
  • Note that this avoids the need to create empty definitions for unused events
  • See (page 360)
gui components
GUI Components
  • A GUI component is an object that represents a visual entity in an graphical user interface (such as a button or slider)
  • Components can generate events to which listener objects can respond
  • For example, an applet is a component that can generate mouse events
  • An applet is also a special kind of component, called a container, in which other components can be placed
gui components73
GUI Components
  • See (page 363)
  • Components are organized into an inheritance class hierarchy so that they can easily share characteristics
  • When we define certain methods, such as the paint method of an applet, we are actually overriding a method defined in the Component class, which is ultimately inherited into the Applet class
  • See (page 367)
  • See (page 369)