SlideShare a Scribd company logo
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("=================");
    }
…

}

More Related Content

PPT
Unit i
PPT
oops-1
PPT
JavaYDL11
PPT
Inheritance
PDF
Lecture Notes
PDF
C h 04 oop_inheritance
PPT
PPT
Unit i
oops-1
JavaYDL11
Inheritance
Lecture Notes
C h 04 oop_inheritance

What's hot (19)

PPT
DOCX
Unit3 java
PPTX
03 classes interfaces_principlesofoop
PDF
PDF
Core java complete notes - Contact at +91-814-614-5674
DOCX
Java sessionnotes
PDF
Java unit2
PPTX
Inheritance
PPT
C++ Inheritance
PPT
Java Programming - Inheritance
PPTX
Java class 6
PPTX
Class introduction in java
PDF
Class notes(week 6) on inheritance and multiple inheritance
PPS
Introduction to class in java
PPTX
Java chapter 4
PPT
04inherit
PPTX
03 object-classes-pbl-4-slots
PPTX
Java chapter 5
PPTX
00ps inheritace using c++
Unit3 java
03 classes interfaces_principlesofoop
Core java complete notes - Contact at +91-814-614-5674
Java sessionnotes
Java unit2
Inheritance
C++ Inheritance
Java Programming - Inheritance
Java class 6
Class introduction in java
Class notes(week 6) on inheritance and multiple inheritance
Introduction to class in java
Java chapter 4
04inherit
03 object-classes-pbl-4-slots
Java chapter 5
00ps inheritace using c++
Ad

Viewers also liked (10)

DOC
Lab 4 jawapan (sugentiran mane)
PPTX
abitha-pds inheritance presentation
PPT
Lecture4
PPT
Inheritance & Polymorphism - 1
PPT
PPT
Inheritance
PPT
Inheritance, polymorphisam, abstract classes and composition)
PPSX
PPT
169 Ch 29_lecture_presentation
PPTX
Inheritance
Lab 4 jawapan (sugentiran mane)
abitha-pds inheritance presentation
Lecture4
Inheritance & Polymorphism - 1
Inheritance
Inheritance, polymorphisam, abstract classes and composition)
169 Ch 29_lecture_presentation
Inheritance
Ad

Similar to Chapter 04 inheritance (20)

PPT
M251_Meeting 5 (Inheritance and Polymorphism).ppt
DOCX
Sdtl assignment 03
PPTX
Inheritance in java
PPT
Java inheritance
PPT
Chapter 8 Inheritance
PPT
Basics of inheritance .22
PPTX
Chapter 8.1
PPTX
Java Inheritance - sub class constructors - Method overriding
PPT
Unit 3 Java
PDF
PPTX
‫Chapter3 inheritance
PDF
javainheritance
PPT
RajLec10.ppt
PPT
Chap11
DOCX
Class notes(week 6) on inheritance and multiple inheritance
PPT
9781439035665 ppt ch10
PPT
6.INHERITANCE.ppt(MB).ppt .
PPTX
Inheritance Slides
PPTX
10. inheritance
M251_Meeting 5 (Inheritance and Polymorphism).ppt
Sdtl assignment 03
Inheritance in java
Java inheritance
Chapter 8 Inheritance
Basics of inheritance .22
Chapter 8.1
Java Inheritance - sub class constructors - Method overriding
Unit 3 Java
‫Chapter3 inheritance
javainheritance
RajLec10.ppt
Chap11
Class notes(week 6) on inheritance and multiple inheritance
9781439035665 ppt ch10
6.INHERITANCE.ppt(MB).ppt .
Inheritance Slides
10. inheritance

Recently uploaded (20)

PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPT
Teaching material agriculture food technology
PPTX
Programs and apps: productivity, graphics, security and other tools
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Spectroscopy.pptx food analysis technology
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Encapsulation theory and applications.pdf
PPTX
1. Introduction to Computer Programming.pptx
PPTX
Tartificialntelligence_presentation.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPTX
Machine Learning_overview_presentation.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Unlocking AI with Model Context Protocol (MCP)
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Per capita expenditure prediction using model stacking based on satellite ima...
Teaching material agriculture food technology
Programs and apps: productivity, graphics, security and other tools
“AI and Expert System Decision Support & Business Intelligence Systems”
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Assigned Numbers - 2025 - Bluetooth® Document
Digital-Transformation-Roadmap-for-Companies.pptx
Spectroscopy.pptx food analysis technology
MYSQL Presentation for SQL database connectivity
Encapsulation theory and applications.pdf
1. Introduction to Computer Programming.pptx
Tartificialntelligence_presentation.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
NewMind AI Weekly Chronicles - August'25-Week II
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Machine Learning_overview_presentation.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Unlocking AI with Model Context Protocol (MCP)

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("================="); } … }