SlideShare una empresa de Scribd logo
1 de 43
Descargar para leer sin conexión
1




Chapter 04: Inheritance
2




Objectives
• Learn about the concept of inheritance
• Extend classes
• Override superclass methods
• Understand how constructors are called during
  inheritance
• Use superclass constructors that require arguments
• Access superclass methods
• Learn which methods you cannot override
3




Learning About the Concept
of Inheritance
• Inheritance
  ▫ Mechanism that enables one class to inherit behavior
    and attributes of another class
  ▫ Apply knowledge of general category to more specific
    objects
4




Concept of Inheritance
5
6




• Use inheritance to create derived class
  ▫ Save time
  ▫ Reduce errors
  ▫ Reduce amount of new learning required to use new
    class
7




• Base class
  ▫ Used as a basis for inheritance
  ▫ Also called:
     Superclass
     Parent class
8




Learning About the Concept
of Inheritance (continued)
• Derived class
  ▫ Inherits from a base class
  ▫ Always “is a” case or example of more general base
    class
  ▫ Also called:
     Subclass
     Child class
9




Extending Classes
• Keyword extends
  ▫ Achieve inheritance in Java
  ▫ Example:
     public class EmployeeWithTerritory
     extends Employee
• Inheritance one-way proposition
  ▫ Child inherits from parent, not other way around
• Subclasses more specific
• instanceof keyword
10




Extending Classes
11



Quick Quiz
1. ____ is the principle that allows you to apply
   your knowledge of a general category to more
   specific objects.

2. True or False: A class diagram consists of a
rectangle divided into five sections.

3. You use the keyword ____ to achieve inheritance
in Java.
12




Extra notes
Inheritance Relationship
• The inheritance relationship can be viewed as a
  relationship between an object category and its
  subcategories.

  ▫ For example...
Inheritance Relationship
     Transport
Inheritance Relationship
         Transport
 Air Transport
Inheritance Relationship
         Transport
 Air Transport          Sea
                     Transport
Inheritance Relationship
         Transport
 Air Transport          Sea
                     Transport




    Land Transport
Inheritance Relationship
• The inheritance relationship is sometimes
  called the “is-a” relationship.

 ▫ For example...
Inheritance Relationship
                       Transport

                                   Inheritance Relationship



   Sea Transport     Land Transport          Air Transport




   Sea Transport     Land Transport          Air Transport
    object “is a”      object “is a”          object “is a”
  Transport object   Transport object       Transport object
Inheritance Relationship
• Based on the meaning of the “is-a” relationship,
  each object will have attributes and behaviour as
  defined by its category and all its supercategories.

• An inheritance hierarchy can be built through
  generalization or specialization.
Inheritance Relationship
                Transport
                            Attributes
       speed
                                speed
       getSpeed( )
                                altitude



           Air Transport
                            Behaviour
                               getSpeed()
       altitude
       fly( )
                               fly()
Subclassing
• Java supports class inheritance through
  subclassing.
• By declaring a class as a subclass of a base class, an
  inheritance relationship between those two classes
  is created.
• The Java keyword for this is extends.
Subclassing
           class Rectangle {
               private int width, height;
               public Rectangle(int w, int h) {
                  width = w;
                  height = h;
               }
               public int getArea() {
                  return width * height;

               }
           }
           class Square extends Rectangle {
                                                  Base
subclass   }                                      class
Subclassing
• In the example, the Square class is declared as a
  subclass of the Rectangle class
• Each subclass inherits the instance variables and
  instance methods of its base class.
• Note that constructors and private methods ARE NOT
  INHERITED.
• Besides attributes and methods inherited from its base
  class, a subclass can also define its own attributes and
  methods.
Subclassing
 class AudioPlayer {
   class AudioPlayer {
     private String audioFilename;
      private String audioFilename;
     public AudioPlayer() {…}
      public AudioPlayer() {…}
     public void play() {…}
      public void play() {…}
     private void convert() {…}
      private void convert() {…}
 }
   }
 class MP3Player extends AudioPlayer { {
  class MP3Player extends AudioPlayer
    private boolean encrypted;
     private boolean encrypted;
    public MP3Player() {…}
     public MP3Player() {…}
 }}

                          Attributes:      audioFilename
                                           encrypted
  : MP3Player             Constructor:
                                        MP3Player()
                          Instance method:
                                        play()
Constructors and super()
• Although a subclass inherits private attributes from its
  base class, it has no direct access to them. How will the
  subclass be able to initialize those attributes in its
  constructors?
• Every constructor defined in a subclass must “call” one
  of the constructors of its base class. The “call” is
  performed through the super() statement.
• The super() statement must be the first statement in
  the constructor method.
Constructors and super()
         class Rectangle {
             private int width, height;

             public Rectangle(int w, int h) {
                width = w;
                height = h;
             }

             public int getArea() {
                return width * height;

         }   }
         class Square extends Rectangle {          “Calls” the
                                                constructor of the
             public Square(int size) {           Rectangle class
                super(size, size);
             }
         }
Constructors and super()
• Note that if there is no super() statement in
  a constructor, the compiler will automatically
  insert a super() statement with no
  parameters.
Constructors and super()
class Rectangle {                         class Square extends Rectangle
                                          {
    private int width, height;               public Square(int size) {
                                                  setWidth(size);
    public Rectangle(int w, int h) {
                                                  setHeight(size);
       width = w;
                                             }
       height = h;
    }
                                          }     Compiler secretly adds
    public void setWidth(int w) {                    a super()!
       width = w;
    }
                                 The compiler then displays this error
    public void setHeight(int h) {
       height = h;               message. Why?
    }                              test.java: 16: cannot resolve symbol
                                   symbol : constructor Rectangle ()
}                                  location: class Rectangle
                                   public Square(int size) {
                                                        ^
Benefits of Inheritance
• Reduces redundant code and code modifications
  ▫ A base class defines attributes and methods which
    are inherited by all of its subclasses. This leads to a
    reduction of redundant code and code
    modifications.
• Makes your program easier to extend
  ▫ When adding a new subclass, we only need to define
    attributes and methods which are specific to objects
    of that class.
Benefits of Inheritance
 • Increases code reuse
    ▫ Example: The Java library has a JButton class. We
      can create a subclass of the JButton class to define
      objects which are like JButton objects but with
      additional attributes and methods.
    ▫ This is possible even though we do not have access
      to the source code for the JButton class.
Method Overriding
• A subclass sometimes inherits instance
  methods whose implementation is not
  suitable for its instances.

 For example …
class Circle {
    private int radius;

    public Circle(int r) {
       radius = r;
    }
    public double getArea( ) {
       System.out.print("(Area calculated in Circle::getArea()) ");
       return 22.0/7*radius*radius;
}   }


class Point extends Circle {
                                       The Point class inherits
    private int x, y;
                                       the radius attribute and
    public Point(int px, int py)       the getArea() method
    {                                    from its base class.
       super(0);
       x = px;
       y = py;
    }
}
class Application {
        public static void main(String[ ] args) {
           Circle circle = new Circle(7);
           Point pt = new Point(100, 50);
           System.out.println(“Area of circle: "+circle.getArea());
           System.out.println("Area of point: "+pt.getArea());
        }
    }

        Output:
           (Area calculated in Circle::getArea()) Area of circle: 154.0
           (Area calculated in Circle::getArea()) Area of point: 0.0


• The area for any Point object is zero. For efficiency,
  it is unnecessary to calculate the area; simply return
  the value 0.
Method Overriding
• Java supports method overriding. Method
  overriding means replacing the
  implementation of an inherited method with
  another implementation.
• To override a method, we simply redefine the
  method in the subclass.

• For example …
class Circle {
    private int radius;

    public Circle(int r) {
        radius = r;
    }

    public double getArea( ) {
        System.out.print("(Area calculated in Circle::getArea()) ");
        return 22.0/7*radius*radius;
    }
}
class Point extends Circle {
    private int x, y;                               Method getArea()
                                                        overriden
     public Point(int px, int py) {
         super(0);
         x = px;                        Returns 0
         y = py;
     }
     public double getArea( ) {
         System.out.print("(Area calculated in Point::getArea()) ");
         return 0;
     }
}
Method Overriding
        class Application {
            public static void main(String[ ] args) {
                Circle circle = new Circle(7);
                Point pt = new Point(100, 50);
                System.out.println(“Area of circle: "+circle.getArea());
                System.out.println("Area of point: "+pt.getArea());
            }
        }


  Output:
     (Area calculated in Circle::getArea()) Area of circle: 154.0
     (Area calculated in Point::getArea()) Area of point: 0.0
Method Overriding hierarchy:
• Consider the following inheritance
                          A
                                      D objD = new D();
                       doThis()
                                      E objE = new E();
                                      B objB = new B();
                   C              D   objE.doThis();
               doThis()               objD.doThis();
                                      objB.doThis();
           E              F
        doThis()

                          B
The super keyword again…
• Consider the following class definitions:
      class Rectangle {
               …
           private int width, height;

           public Rectangle(int w, int h) {
              width = w;
              height = h;
           }

           public void display( ) {
              for (int row=0; row < height; row++) {
                    for (int col=0; col < width; col++)
                          System.out.print('*');
                    System.out.println();
              }
           }
              …
      }
Rectangle class is
                                              the base class for
                                                this subclass
class LabelledRectangle extends Rectangle {

    private String label;

    public LabelledRectangle(int w, int h, String str) {
        super(w, h);
        label = str;                        Overrides display()
    }                                     method inherited from
                                              the base class
    public void display( ) {
        System.out.println("=================");
        for (int row=0; row < height; row++) {
              for (int col=0; col < width; col++)
                    System.out.print('*');
              System.out.println();
        }
        System.out.println(label);
        System.out.println("=================");
    }

    …
}
Method Overriding
         class Application {
             public static void main(String[ ] args) {
                 Rectangle rect1 = new Rectangle(3, 3);
                 LabelledRectangle rect2;
                 rect2 = new LabelledRectangle(2, 3, "Block");
                 rect1.display();
                 System.out.println();
                 rect2.display();
             }
         }


***
***
***
=================
**
**
**
Block
=================
• Observe the body of the display() method in the
  LabelledRectangle class…

     public void display( ) {
        System.out.println("=================");
        for (int row=0; row < getHeight(); row++) {
              for (int col=0; col < getWidth(); col++)
                    System.out.print('*');
              System.out.println();
        }
        System.out.println(label);
        System.out.println("=================");
     }

   Is it possible to “call” the                      Exactly the same as
                                                        the code in the
   overridden display() method                         display() method
   in the Rectangle class?                            inherited from the
                                                          base class
• We can “call” the overridden method by using the
  super keyword as follows:

class LabelledRectangle extends Rectangle {                Executes the
    private String label;                                  overridden method

    public LabelledRectangle(int w, int h, String str) {
        super(w, h);
        label = str;
    }

    public void display( ) {
        System.out.println("=================");
        super.display();
        System.out.println(label);
        System.out.println("=================");
    }
…

}

Más contenido relacionado

La actualidad más candente

La actualidad más candente (19)

08slide
08slide08slide
08slide
 
Unit3 java
Unit3 javaUnit3 java
Unit3 java
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
Java unit2
Java unit2Java unit2
Java unit2
 
Inheritance
InheritanceInheritance
Inheritance
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
 
Java class 6
Java class 6Java class 6
Java class 6
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Java chapter 4
Java chapter 4Java chapter 4
Java chapter 4
 
04inherit
04inherit04inherit
04inherit
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
 

Destacado

Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)Yugeswary
 
abitha-pds inheritance presentation
abitha-pds inheritance presentationabitha-pds inheritance presentation
abitha-pds inheritance presentationabitha ben
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1PRN USM
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)farhan amjad
 
169 Ch 29_lecture_presentation
 169 Ch 29_lecture_presentation 169 Ch 29_lecture_presentation
169 Ch 29_lecture_presentationgwrandall
 

Destacado (10)

Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)
 
abitha-pds inheritance presentation
abitha-pds inheritance presentationabitha-pds inheritance presentation
abitha-pds inheritance presentation
 
Lecture4
Lecture4Lecture4
Lecture4
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Opps
OppsOpps
Opps
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)
 
Inheritance
InheritanceInheritance
Inheritance
 
169 Ch 29_lecture_presentation
 169 Ch 29_lecture_presentation 169 Ch 29_lecture_presentation
169 Ch 29_lecture_presentation
 
Inheritance
InheritanceInheritance
Inheritance
 

Similar a Chapter 04 inheritance

Similar a Chapter 04 inheritance (20)

L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
6.INHERITANCE.ppt(MB).ppt .
6.INHERITANCE.ppt(MB).ppt                    .6.INHERITANCE.ppt(MB).ppt                    .
6.INHERITANCE.ppt(MB).ppt .
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
 
Java
JavaJava
Java
 
Pi j2.2 classes
Pi j2.2 classesPi j2.2 classes
Pi j2.2 classes
 
Java2
Java2Java2
Java2
 
Inheritance
InheritanceInheritance
Inheritance
 
7_-_Inheritance
7_-_Inheritance7_-_Inheritance
7_-_Inheritance
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
Better Understanding OOP using C#
Better Understanding OOP using C#Better Understanding OOP using C#
Better Understanding OOP using C#
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Abstraction
AbstractionAbstraction
Abstraction
 
9 cm604.14
9 cm604.149 cm604.14
9 cm604.14
 
Java OO Revisited
Java OO RevisitedJava OO Revisited
Java OO Revisited
 
10. inheritance
10. inheritance10. inheritance
10. inheritance
 

Último

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 

Último (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 

Chapter 04 inheritance

  • 2. 2 Objectives • Learn about the concept of inheritance • Extend classes • Override superclass methods • Understand how constructors are called during inheritance • Use superclass constructors that require arguments • Access superclass methods • Learn which methods you cannot override
  • 3. 3 Learning About the Concept of Inheritance • Inheritance ▫ Mechanism that enables one class to inherit behavior and attributes of another class ▫ Apply knowledge of general category to more specific objects
  • 5. 5
  • 6. 6 • Use inheritance to create derived class ▫ Save time ▫ Reduce errors ▫ Reduce amount of new learning required to use new class
  • 7. 7 • Base class ▫ Used as a basis for inheritance ▫ Also called: Superclass Parent class
  • 8. 8 Learning About the Concept of Inheritance (continued) • Derived class ▫ Inherits from a base class ▫ Always “is a” case or example of more general base class ▫ Also called: Subclass Child class
  • 9. 9 Extending Classes • Keyword extends ▫ Achieve inheritance in Java ▫ Example: public class EmployeeWithTerritory extends Employee • Inheritance one-way proposition ▫ Child inherits from parent, not other way around • Subclasses more specific • instanceof keyword
  • 11. 11 Quick Quiz 1. ____ is the principle that allows you to apply your knowledge of a general category to more specific objects. 2. True or False: A class diagram consists of a rectangle divided into five sections. 3. You use the keyword ____ to achieve inheritance in Java.
  • 13. Inheritance Relationship • The inheritance relationship can be viewed as a relationship between an object category and its subcategories. ▫ For example...
  • 15. Inheritance Relationship Transport Air Transport
  • 16. Inheritance Relationship Transport Air Transport Sea Transport
  • 17. Inheritance Relationship Transport Air Transport Sea Transport Land Transport
  • 18. Inheritance Relationship • The inheritance relationship is sometimes called the “is-a” relationship. ▫ For example...
  • 19. Inheritance Relationship Transport Inheritance Relationship Sea Transport Land Transport Air Transport Sea Transport Land Transport Air Transport object “is a” object “is a” object “is a” Transport object Transport object Transport object
  • 20. Inheritance Relationship • Based on the meaning of the “is-a” relationship, each object will have attributes and behaviour as defined by its category and all its supercategories. • An inheritance hierarchy can be built through generalization or specialization.
  • 21. Inheritance Relationship Transport Attributes speed speed getSpeed( ) altitude Air Transport Behaviour getSpeed() altitude fly( ) fly()
  • 22. Subclassing • Java supports class inheritance through subclassing. • By declaring a class as a subclass of a base class, an inheritance relationship between those two classes is created. • The Java keyword for this is extends.
  • 23. Subclassing class Rectangle { private int width, height; public Rectangle(int w, int h) { width = w; height = h; } public int getArea() { return width * height; } } class Square extends Rectangle { Base subclass } class
  • 24. Subclassing • In the example, the Square class is declared as a subclass of the Rectangle class • Each subclass inherits the instance variables and instance methods of its base class. • Note that constructors and private methods ARE NOT INHERITED. • Besides attributes and methods inherited from its base class, a subclass can also define its own attributes and methods.
  • 25. Subclassing class AudioPlayer { class AudioPlayer { private String audioFilename; private String audioFilename; public AudioPlayer() {…} public AudioPlayer() {…} public void play() {…} public void play() {…} private void convert() {…} private void convert() {…} } } class MP3Player extends AudioPlayer { { class MP3Player extends AudioPlayer private boolean encrypted; private boolean encrypted; public MP3Player() {…} public MP3Player() {…} }} Attributes: audioFilename encrypted : MP3Player Constructor: MP3Player() Instance method: play()
  • 26. Constructors and super() • Although a subclass inherits private attributes from its base class, it has no direct access to them. How will the subclass be able to initialize those attributes in its constructors? • Every constructor defined in a subclass must “call” one of the constructors of its base class. The “call” is performed through the super() statement. • The super() statement must be the first statement in the constructor method.
  • 27. Constructors and super() class Rectangle { private int width, height; public Rectangle(int w, int h) { width = w; height = h; } public int getArea() { return width * height; } } class Square extends Rectangle { “Calls” the constructor of the public Square(int size) { Rectangle class super(size, size); } }
  • 28. Constructors and super() • Note that if there is no super() statement in a constructor, the compiler will automatically insert a super() statement with no parameters.
  • 29. Constructors and super() class Rectangle { class Square extends Rectangle { private int width, height; public Square(int size) { setWidth(size); public Rectangle(int w, int h) { setHeight(size); width = w; } height = h; } } Compiler secretly adds public void setWidth(int w) { a super()! width = w; } The compiler then displays this error public void setHeight(int h) { height = h; message. Why? } test.java: 16: cannot resolve symbol symbol : constructor Rectangle () } location: class Rectangle public Square(int size) { ^
  • 30. Benefits of Inheritance • Reduces redundant code and code modifications ▫ A base class defines attributes and methods which are inherited by all of its subclasses. This leads to a reduction of redundant code and code modifications. • Makes your program easier to extend ▫ When adding a new subclass, we only need to define attributes and methods which are specific to objects of that class.
  • 31. Benefits of Inheritance • Increases code reuse ▫ Example: The Java library has a JButton class. We can create a subclass of the JButton class to define objects which are like JButton objects but with additional attributes and methods. ▫ This is possible even though we do not have access to the source code for the JButton class.
  • 32. Method Overriding • A subclass sometimes inherits instance methods whose implementation is not suitable for its instances. For example …
  • 33. class Circle { private int radius; public Circle(int r) { radius = r; } public double getArea( ) { System.out.print("(Area calculated in Circle::getArea()) "); return 22.0/7*radius*radius; } } class Point extends Circle { The Point class inherits private int x, y; the radius attribute and public Point(int px, int py) the getArea() method { from its base class. super(0); x = px; y = py; } }
  • 34. class Application { public static void main(String[ ] args) { Circle circle = new Circle(7); Point pt = new Point(100, 50); System.out.println(“Area of circle: "+circle.getArea()); System.out.println("Area of point: "+pt.getArea()); } } Output: (Area calculated in Circle::getArea()) Area of circle: 154.0 (Area calculated in Circle::getArea()) Area of point: 0.0 • The area for any Point object is zero. For efficiency, it is unnecessary to calculate the area; simply return the value 0.
  • 35. Method Overriding • Java supports method overriding. Method overriding means replacing the implementation of an inherited method with another implementation. • To override a method, we simply redefine the method in the subclass. • For example …
  • 36. class Circle { private int radius; public Circle(int r) { radius = r; } public double getArea( ) { System.out.print("(Area calculated in Circle::getArea()) "); return 22.0/7*radius*radius; } } class Point extends Circle { private int x, y; Method getArea() overriden public Point(int px, int py) { super(0); x = px; Returns 0 y = py; } public double getArea( ) { System.out.print("(Area calculated in Point::getArea()) "); return 0; } }
  • 37. Method Overriding class Application { public static void main(String[ ] args) { Circle circle = new Circle(7); Point pt = new Point(100, 50); System.out.println(“Area of circle: "+circle.getArea()); System.out.println("Area of point: "+pt.getArea()); } } Output: (Area calculated in Circle::getArea()) Area of circle: 154.0 (Area calculated in Point::getArea()) Area of point: 0.0
  • 38. Method Overriding hierarchy: • Consider the following inheritance A D objD = new D(); doThis() E objE = new E(); B objB = new B(); C D objE.doThis(); doThis() objD.doThis(); objB.doThis(); E F doThis() B
  • 39. The super keyword again… • Consider the following class definitions: class Rectangle { … private int width, height; public Rectangle(int w, int h) { width = w; height = h; } public void display( ) { for (int row=0; row < height; row++) { for (int col=0; col < width; col++) System.out.print('*'); System.out.println(); } } … }
  • 40. Rectangle class is the base class for this subclass class LabelledRectangle extends Rectangle { private String label; public LabelledRectangle(int w, int h, String str) { super(w, h); label = str; Overrides display() } method inherited from the base class public void display( ) { System.out.println("================="); for (int row=0; row < height; row++) { for (int col=0; col < width; col++) System.out.print('*'); System.out.println(); } System.out.println(label); System.out.println("================="); } … }
  • 41. Method Overriding class Application { public static void main(String[ ] args) { Rectangle rect1 = new Rectangle(3, 3); LabelledRectangle rect2; rect2 = new LabelledRectangle(2, 3, "Block"); rect1.display(); System.out.println(); rect2.display(); } } *** *** *** ================= ** ** ** Block =================
  • 42. • Observe the body of the display() method in the LabelledRectangle class… public void display( ) { System.out.println("================="); for (int row=0; row < getHeight(); row++) { for (int col=0; col < getWidth(); col++) System.out.print('*'); System.out.println(); } System.out.println(label); System.out.println("================="); } Is it possible to “call” the Exactly the same as the code in the overridden display() method display() method in the Rectangle class? inherited from the base class
  • 43. • We can “call” the overridden method by using the super keyword as follows: class LabelledRectangle extends Rectangle { Executes the private String label; overridden method public LabelledRectangle(int w, int h, String str) { super(w, h); label = str; } public void display( ) { System.out.println("================="); super.display(); System.out.println(label); System.out.println("================="); } … }