SlideShare uma empresa Scribd logo
1 de 34
Inheritance

 Chapter 9




              1
Module Outcomes
• To develop a subclass from a superclass
  through inheritance
• To invoke the superclass’s constructors and
  methods using the super keyword
• To override methods in the subclass
• To explore the useful methods (equals(Object),
  hashCode(), toString(), finalize(), clone(), and
  getClass()) in the Object class
• To comprehend polymorphism, dynamic
  binding, and generic programming
                                     2
Module Outcomes
• To describe casting and explain why
  explicit downcasting is necessary
• To understand the effect of hiding data
  fields and static methods
• To restrict access to data and methods
  using the protected visibility modifier
• To declare constants, unmodifiable
  methods, and nonextendable class using
  the final modifier
                               3
Superclasses and Subclasses




               Superclass       Subclass

                 Circle         Cylinder
UML Diagram   -radius
                            -length
              +getRadius
              +setRadius    +getLength
              +findArea     +setLength
                            +findVolume
                            4
// Cylinder.java: Class definition for describing Cylinder
public class Cylinder extends Circle {
  private double length = 1;
                                               Superclass                 Subclass
                                  supertype                     subtype
    /** Return length */
                                                 Circle                   Cylinder
    public double getLength() {               -radius
      return length;                                                  -length
                                              +getRadius
    }                                         +setRadius              +getLength
                                              +findArea               +setLength
                                                                      +findVolume
    /** Set length */
    public void setLength(double length) {
      this.length = length;
    }

    /** Return the volume of this cylinder */
    public double findVolume() {
      return findArea() * length;
    }
}

                                                            5
Cylinder cylinder = new Cylinder();
  System.out.println("The length is " +
    cylinder.getLength());
  System.out.println("The radius is " +
    cylinder.getRadius());
  System.out.println("The volume of the cylinder is " +
    cylinder.findVolume());
  System.out.println("The area of the circle is " +
    cylinder.findArea());


The output is

  The   length is 1.0
  The   radius is 1.0
  The   volume of the cylinder is 3.14159
  The   area of the circle is 3.14159


                                            6
Using the Keyword super
The keyword super refers to the superclass
of the class in which super appears. This
keyword can be used in two ways:
• To call a superclass constructor
• To call a superclass method




                                     7
CAUTION: to call superclass
    constructor from subclass
•Must use super
•Cannot call a superclass constructor’s
name in a subclass – syntax error
•statement that uses the keyword super
must appear first in the constructor.


                                 8
NOTE
•Properties and methods of superclass are inherited in
subclass
• Superclass's constructors are NOT inherited in the
subclass
•Superclass's constructors can only be invoked from the
subclasses' constructors, using super.
•If the keyword super is not explicitly used, the
superclass's no-arg constructor is automatically
invoked.

                                          9
Superclass’s Constructor Is Always
                   Invoked
A constructor may invoke an overloaded constructor or its
superclass’s constructor. If none of them is invoked
explicitly, the compiler puts super() as the first statement
in the constructor. For example,

  public Cylinder() {
                         Constructor Chaining
                                            public       Cylinder() {
                             is equivalent to
  }                                                 super();
                                                }



  public A(double d) {                          public A(double d) {
    // some statements       is equivalent to
                                                  super();
  }                                               // some statements
                                                }


                                                        10
Run project CircleCylinder

   Study the code and design
          various tests



                          11
How is inheritance made
       possible?
    Constructor chaining




                           12
Constructor Chaining
Constructing an instance of a class invokes all the superclasses’ constructors
along the inheritance chain. This is called constructor chaining.
Example:




                                                               13
Constructor Chaining
public class Faculty extends Employee {
  public static void main(String[] args) {
    new Faculty();
  }

    public Faculty() { // no overloaded constructor nor super(), so call super();
      System.out.println("Faculty's no-arg constructor is invoked");
    }
}

class Employee extends Person {
  public Employee() { // calls overloaded constructor, no super() added
    this("Invoke Employee’s overloaded constructor");
    System.out.println("Employee's no-arg constructor is invoked");
  }

    public Employee(String s) { // statement only, call super();
      System.out.println(s);
    }
}

class Person {
  public Person() { // statement only. Insert super(); which does nothing
    System.out.println("Person's no-arg constructor is invoked");

}
  }
                                                             14
animation
                           Trace Execution
public class Faculty extends Employee {
  public static void main(String[] args) {
    new Faculty();                                     1. Start from the
  }                                                      main method
    public Faculty() {
      System.out.println("(4) Faculty's no-arg constructor is invoked");
    }
}

class Employee extends Person {
  public Employee() {
    this("(2) Invoke Employee’s overloaded constructor");
    System.out.println("(3) Employee's no-arg constructor is invoked");
  }

    public Employee(String s) {
      System.out.println(s);
    }
}

class Person {
  public Person() {
    System.out.println("(1) Person's no-arg constructor is invoked");
  }
}
                                                             15
animation
                           Trace Execution
public class Faculty extends Employee {
  public static void main(String[] args) {
    new Faculty();                                     2. Invoke Faculty
  }                                                        constructor
    public Faculty() {
      System.out.println("(4) Faculty's no-arg constructor is invoked");
    }
}

class Employee extends Person {
  public Employee() {
    this("(2) Invoke Employee’s overloaded constructor");
    System.out.println("(3) Employee's no-arg constructor is invoked");
  }

    public Employee(String s) {
      System.out.println(s);
    }
}

class Person {
  public Person() {
    System.out.println("(1) Person's no-arg constructor is invoked");
  }
}
                                                             16
animation
                           Trace Execution
public class Faculty extends Employee {
  public static void main(String[] args) {
    new Faculty();
  }

    public Faculty() {
      System.out.println("(4) Faculty's no-arg constructor is invoked");
    }
}                                                    3. Invoke Employee’s no-
                                                           arg constructor
class Employee extends Person {
  public Employee() {
    this("(2) Invoke Employee’s overloaded constructor");
    System.out.println("(3) Employee's no-arg constructor is invoked");
  }

    public Employee(String s) {
      System.out.println(s);
    }
}

class Person {
  public Person() {
    System.out.println("(1) Person's no-arg constructor is invoked");
  }
}
                                                             17
animation
                           Trace Execution
public class Faculty extends Employee {
  public static void main(String[] args) {
    new Faculty();
  }

    public Faculty() {
      System.out.println("(4) Faculty's no-arg constructor is invoked");
    }
}
                                                  4. Invoke Employee(String)
class Employee extends Person {                           constructor
  public Employee() {
    this("(2) Invoke Employee’s overloaded constructor");
    System.out.println("(3) Employee's no-arg constructor is invoked");
  }

    public Employee(String s) {
      System.out.println(s);
    }
}

class Person {
  public Person() {
    System.out.println("(1) Person's no-arg constructor is invoked");
  }
}
                                                             18
animation
                           Trace Execution
public class Faculty extends Employee {
  public static void main(String[] args) {
    new Faculty();
  }

    public Faculty() {
      System.out.println("(4) Faculty's no-arg constructor is invoked");
    }
}

class Employee extends Person {
  public Employee() {
    this("(2) Invoke Employee’s overloaded constructor");
    System.out.println("(3) Employee's no-arg constructor is invoked");
  }

    public Employee(String s) {
      System.out.println(s);
    }
}
                                                       5. Invoke Person()
                                                           constructor
class Person {
  public Person() {
    System.out.println("(1) Person's no-arg constructor is invoked");
  }
}
                                                             19
animation
                           Trace Execution
public class Faculty extends Employee {
  public static void main(String[] args) {
    new Faculty();
  }

    public Faculty() {
      System.out.println("(4) Faculty's no-arg constructor is invoked");
    }
}

class Employee extends Person {
  public Employee() {
    this("(2) Invoke Employee’s overloaded constructor");
    System.out.println("(3) Employee's no-arg constructor is invoked");
  }

    public Employee(String s) {
      System.out.println(s);
    }
}                                                      6. Execute println
class Person {
  public Person() {
    System.out.println("(1) Person's no-arg constructor is invoked");
  }
}
                                                             20
animation
                           Trace Execution
public class Faculty extends Employee {
  public static void main(String[] args) {
    new Faculty();
  }

    public Faculty() {
      System.out.println("(4) Faculty's no-arg constructor is invoked");
    }
}

class Employee extends Person {
  public Employee() {
    this("(2) Invoke Employee’s overloaded constructor");
    System.out.println("(3) Employee's no-arg constructor is invoked");
  }

    public Employee(String s) {
      System.out.println(s);
    }
}
                                                       7. Execute println
class Person {
  public Person() {
    System.out.println("(1) Person's no-arg constructor is invoked");
  }
}
                                                             21
animation
                           Trace Execution
public class Faculty extends Employee {
  public static void main(String[] args) {
    new Faculty();
  }

    public Faculty() {
      System.out.println("(4) Faculty's no-arg constructor is invoked");
    }
}

class Employee extends Person {
  public Employee() {
    this("(2) Invoke Employee’s overloaded constructor");
    System.out.println("(3) Employee's no-arg constructor is invoked");
  }

    public Employee(String s) {
      System.out.println(s);
    }
}
                                                       8. Execute println
class Person {
  public Person() {
    System.out.println("(1) Person's no-arg constructor is invoked");
  }
}
                                                             22
animation
                           Trace Execution
public class Faculty extends Employee {
  public static void main(String[] args) {
    new Faculty();
  }

    public Faculty() {
      System.out.println("(4) Faculty's no-arg constructor is invoked");
    }
}
                                                        9. Execute println
class Employee extends Person {
  public Employee() {
    this("(2) Invoke Employee’s overloaded constructor");
    System.out.println("(3) Employee's no-arg constructor is invoked");
  }

    public Employee(String s) {
      System.out.println(s);
    }
}

class Person {
  public Person() {
    System.out.println("(1) Person's no-arg constructor is invoked");
  }
}
                                                             23
Order of invoking constructors
• See BJ_Faculty_0




                        24
Example on the Impact of a Superclass
      without no-arg Constructor
Find out the errors in the program:
public class Apple extends Fruit {
}

class Fruit {
  public Fruit(String name) {
    System.out.println("Fruit's constructor is invoked");
  }
}
              Will the Apple class compile?
              Run: BJ_Apple_Fruit


                                              25
Check projects
• BJ_Apple_Fruit: Not compiled
   – Fruit: 1-arg constructor
   – Apple: no constructor
• BJ_Apple_Fruit2: Not compiled
   – Fruit: 1-arg constructor
   – Apple: 0-arg constructor
• BJ_Apple_Fruit3: compiled
   – Fruit: 0-arg constructor, 1-arg constructor
   – Apple: 0-arg constructor
• BJ_Apple_Fruit4: compiled
   – Fruit: 1-arg constructor
   – Apple: super(1-arg)


                                                   26
Declaring a Subclass
A subclass extends properties and methods
   from the superclass. You can also:
  Add new properties
  Add new methods
  Override the methods of the superclass
Question: Can we treat a subclass as a
  subset of its parent class?

                                27
Overriding Methods in the
                           Superclass
A subclass inherits methods from a superclass. Sometimes it is
necessary for the subclass to modify the implementation of a method
defined in the superclass. This is referred to as method overriding.
// Cylinder.java: New cylinder class that overrides the findArea()
// method defined in the circle class.
public class Cylinder extends Circle {


 /** Return the surface area of this cylinder. The formula is
    * 2 * circle area + cylinder body area
    */
    public double findArea() {
         return 2 * super.findArea() + 2 * getRadius() * Math.PI * length;
    }


    // Other methods are omitted
}                                                               28
NOTE
•An instance method can be overridden only if it is
accessible.
   •private method m() in superclass
   •private method m() in subclass cannot override the
   m() in superclass
      •The two m() are unrelated




                                           29
Examples
• Class A and subclass B both contain
  method show()
  – Method_Overriding project
    • Show() in B overrides show() in A
• How to call the show() method of A from
  B?
    • To_Bypass_Overriding project
    • Show() in B calls show() in A by calling
      super.show()

                                           30
NOTE
How about static methods in superclass?
•a static method can be inherited
•a static method cannot be overridden
•If you redefine a static method in a subclass, the
method defined in the superclass is hidden.
•See staticMethodOverride.java


                                        31
Check:
•   BJ_Method_Overriding
•   BJ_Method_Overriding1
•   BJ_Method_Overriding2
•   Overriding_vs_Overloading




                                32
The Object Class
 All Java classes descend from the
 java.lang.Object class.
 If no inheritance is specified when a class
 is defined, the superclass of the class is
 Object.

public class Circle {                public class Circle extends Object {
                        Equivalent
  ...                                  ...
}                                    }




                                                     33
The toString() method in
                   Object
The toString() method returns a string representation of
the object. Default implementation returns:

a string with class name of the object is an instance, @,
and a number representing this object. Ex:
  Cylinder myCylinder = new Cylinder(5.0, 2.0);

  System.out.println(myCylinder.toString());


 displays something like Cylinder@15037e5.

 - not very helpful or informative.

 - should override the toString method to a more meaning string


                                                       34

Mais conteúdo relacionado

Mais procurados

Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectOUM SAOKOSAL
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbookManusha Dilan
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceOUM SAOKOSAL
 
Python Metaprogramming
Python MetaprogrammingPython Metaprogramming
Python MetaprogrammingSDU CYBERLAB
 
Hacking JavaFX with Groovy, Clojure, Scala, and Visage
Hacking JavaFX with Groovy, Clojure, Scala, and VisageHacking JavaFX with Groovy, Clojure, Scala, and Visage
Hacking JavaFX with Groovy, Clojure, Scala, and VisageStephen Chin
 
JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011Stephen Chin
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?Henri Tremblay
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCOUM SAOKOSAL
 
The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202Mahmoud Samir Fayed
 
Swift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : ProtocolSwift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : ProtocolKwang Woo NAM
 
Clojure: Functional Concurrency for the JVM (presented at OSCON)
Clojure: Functional Concurrency for the JVM (presented at OSCON)Clojure: Functional Concurrency for the JVM (presented at OSCON)
Clojure: Functional Concurrency for the JVM (presented at OSCON)Howard Lewis Ship
 
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...Stephen Chin
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your GroovyAlonso Torres
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPrashant Rane
 
Classboxes
ClassboxesClassboxes
ClassboxesESUG
 
Clojure: Functional Concurrency for the JVM (presented at Open Source Bridge)
Clojure: Functional Concurrency for the JVM (presented at Open Source Bridge)Clojure: Functional Concurrency for the JVM (presented at Open Source Bridge)
Clojure: Functional Concurrency for the JVM (presented at Open Source Bridge)Howard Lewis Ship
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 

Mais procurados (20)

Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
 
Python Metaprogramming
Python MetaprogrammingPython Metaprogramming
Python Metaprogramming
 
Hacking JavaFX with Groovy, Clojure, Scala, and Visage
Hacking JavaFX with Groovy, Clojure, Scala, and VisageHacking JavaFX with Groovy, Clojure, Scala, and Visage
Hacking JavaFX with Groovy, Clojure, Scala, and Visage
 
JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Swift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : ProtocolSwift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : Protocol
 
Clojure: Functional Concurrency for the JVM (presented at OSCON)
Clojure: Functional Concurrency for the JVM (presented at OSCON)Clojure: Functional Concurrency for the JVM (presented at OSCON)
Clojure: Functional Concurrency for the JVM (presented at OSCON)
 
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
Classboxes
ClassboxesClassboxes
Classboxes
 
Clojure: Functional Concurrency for the JVM (presented at Open Source Bridge)
Clojure: Functional Concurrency for the JVM (presented at Open Source Bridge)Clojure: Functional Concurrency for the JVM (presented at Open Source Bridge)
Clojure: Functional Concurrency for the JVM (presented at Open Source Bridge)
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 

Semelhante a 7 inheritance

C h 04 oop_inheritance
C h 04 oop_inheritanceC h 04 oop_inheritance
C h 04 oop_inheritanceshatha00
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 InheritanceOUM SAOKOSAL
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - InheritanceOum Saokosal
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorialBui Kiet
 
Java Basics
Java BasicsJava Basics
Java BasicsF K
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.pptEmanAsem4
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingPurvik Rana
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptSeok-joon Yun
 

Semelhante a 7 inheritance (20)

11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
 
C h 04 oop_inheritance
C h 04 oop_inheritanceC h 04 oop_inheritance
C h 04 oop_inheritance
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java
JavaJava
Java
 
Java
JavaJava
Java
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
Java basic
Java basicJava basic
Java basic
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorial
 
Java Day-3
Java Day-3Java Day-3
Java Day-3
 
Java Basics
Java BasicsJava Basics
Java Basics
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 

Mais de Abhijit Gaikwad (11)

Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
20 ch22 collections
20 ch22 collections20 ch22 collections
20 ch22 collections
 
17 sessions
17 sessions17 sessions
17 sessions
 
16 cookies
16 cookies16 cookies
16 cookies
 
15 decorator pattern
15 decorator pattern15 decorator pattern
15 decorator pattern
 
12 memory hierarchy
12 memory hierarchy12 memory hierarchy
12 memory hierarchy
 
12 cache questions
12 cache questions12 cache questions
12 cache questions
 
10 strategy pattern
10 strategy pattern10 strategy pattern
10 strategy pattern
 
9 abstract interface
9 abstract interface9 abstract interface
9 abstract interface
 
8 polymorphism
8 polymorphism8 polymorphism
8 polymorphism
 
4 recursion details
4 recursion details4 recursion details
4 recursion details
 

7 inheritance

  • 2. Module Outcomes • To develop a subclass from a superclass through inheritance • To invoke the superclass’s constructors and methods using the super keyword • To override methods in the subclass • To explore the useful methods (equals(Object), hashCode(), toString(), finalize(), clone(), and getClass()) in the Object class • To comprehend polymorphism, dynamic binding, and generic programming 2
  • 3. Module Outcomes • To describe casting and explain why explicit downcasting is necessary • To understand the effect of hiding data fields and static methods • To restrict access to data and methods using the protected visibility modifier • To declare constants, unmodifiable methods, and nonextendable class using the final modifier 3
  • 4. Superclasses and Subclasses Superclass Subclass Circle Cylinder UML Diagram -radius -length +getRadius +setRadius +getLength +findArea +setLength +findVolume 4
  • 5. // Cylinder.java: Class definition for describing Cylinder public class Cylinder extends Circle { private double length = 1; Superclass Subclass supertype subtype /** Return length */ Circle Cylinder public double getLength() { -radius return length; -length +getRadius } +setRadius +getLength +findArea +setLength +findVolume /** Set length */ public void setLength(double length) { this.length = length; } /** Return the volume of this cylinder */ public double findVolume() { return findArea() * length; } } 5
  • 6. Cylinder cylinder = new Cylinder(); System.out.println("The length is " + cylinder.getLength()); System.out.println("The radius is " + cylinder.getRadius()); System.out.println("The volume of the cylinder is " + cylinder.findVolume()); System.out.println("The area of the circle is " + cylinder.findArea()); The output is The length is 1.0 The radius is 1.0 The volume of the cylinder is 3.14159 The area of the circle is 3.14159 6
  • 7. Using the Keyword super The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways: • To call a superclass constructor • To call a superclass method 7
  • 8. CAUTION: to call superclass constructor from subclass •Must use super •Cannot call a superclass constructor’s name in a subclass – syntax error •statement that uses the keyword super must appear first in the constructor. 8
  • 9. NOTE •Properties and methods of superclass are inherited in subclass • Superclass's constructors are NOT inherited in the subclass •Superclass's constructors can only be invoked from the subclasses' constructors, using super. •If the keyword super is not explicitly used, the superclass's no-arg constructor is automatically invoked. 9
  • 10. Superclass’s Constructor Is Always Invoked A constructor may invoke an overloaded constructor or its superclass’s constructor. If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor. For example, public Cylinder() { Constructor Chaining public Cylinder() { is equivalent to } super(); } public A(double d) { public A(double d) { // some statements is equivalent to super(); } // some statements } 10
  • 11. Run project CircleCylinder Study the code and design various tests 11
  • 12. How is inheritance made possible? Constructor chaining 12
  • 13. Constructor Chaining Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. This is called constructor chaining. Example: 13
  • 14. Constructor Chaining public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { // no overloaded constructor nor super(), so call super(); System.out.println("Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { // calls overloaded constructor, no super() added this("Invoke Employee’s overloaded constructor"); System.out.println("Employee's no-arg constructor is invoked"); } public Employee(String s) { // statement only, call super(); System.out.println(s); } } class Person { public Person() { // statement only. Insert super(); which does nothing System.out.println("Person's no-arg constructor is invoked"); } } 14
  • 15. animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); 1. Start from the } main method public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 15
  • 16. animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); 2. Invoke Faculty } constructor public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 16
  • 17. animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } 3. Invoke Employee’s no- arg constructor class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 17
  • 18. animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } 4. Invoke Employee(String) class Employee extends Person { constructor public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 18
  • 19. animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } 5. Invoke Person() constructor class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 19
  • 20. animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } 6. Execute println class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 20
  • 21. animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } 7. Execute println class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 21
  • 22. animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } 8. Execute println class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 22
  • 23. animation Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } 9. Execute println class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } 23
  • 24. Order of invoking constructors • See BJ_Faculty_0 24
  • 25. Example on the Impact of a Superclass without no-arg Constructor Find out the errors in the program: public class Apple extends Fruit { } class Fruit { public Fruit(String name) { System.out.println("Fruit's constructor is invoked"); } } Will the Apple class compile? Run: BJ_Apple_Fruit 25
  • 26. Check projects • BJ_Apple_Fruit: Not compiled – Fruit: 1-arg constructor – Apple: no constructor • BJ_Apple_Fruit2: Not compiled – Fruit: 1-arg constructor – Apple: 0-arg constructor • BJ_Apple_Fruit3: compiled – Fruit: 0-arg constructor, 1-arg constructor – Apple: 0-arg constructor • BJ_Apple_Fruit4: compiled – Fruit: 1-arg constructor – Apple: super(1-arg) 26
  • 27. Declaring a Subclass A subclass extends properties and methods from the superclass. You can also: Add new properties Add new methods Override the methods of the superclass Question: Can we treat a subclass as a subset of its parent class? 27
  • 28. Overriding Methods in the Superclass A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding. // Cylinder.java: New cylinder class that overrides the findArea() // method defined in the circle class. public class Cylinder extends Circle { /** Return the surface area of this cylinder. The formula is * 2 * circle area + cylinder body area */ public double findArea() { return 2 * super.findArea() + 2 * getRadius() * Math.PI * length; } // Other methods are omitted } 28
  • 29. NOTE •An instance method can be overridden only if it is accessible. •private method m() in superclass •private method m() in subclass cannot override the m() in superclass •The two m() are unrelated 29
  • 30. Examples • Class A and subclass B both contain method show() – Method_Overriding project • Show() in B overrides show() in A • How to call the show() method of A from B? • To_Bypass_Overriding project • Show() in B calls show() in A by calling super.show() 30
  • 31. NOTE How about static methods in superclass? •a static method can be inherited •a static method cannot be overridden •If you redefine a static method in a subclass, the method defined in the superclass is hidden. •See staticMethodOverride.java 31
  • 32. Check: • BJ_Method_Overriding • BJ_Method_Overriding1 • BJ_Method_Overriding2 • Overriding_vs_Overloading 32
  • 33. The Object Class All Java classes descend from the java.lang.Object class. If no inheritance is specified when a class is defined, the superclass of the class is Object. public class Circle { public class Circle extends Object { Equivalent ... ... } } 33
  • 34. The toString() method in Object The toString() method returns a string representation of the object. Default implementation returns: a string with class name of the object is an instance, @, and a number representing this object. Ex: Cylinder myCylinder = new Cylinder(5.0, 2.0); System.out.println(myCylinder.toString()); displays something like Cylinder@15037e5. - not very helpful or informative. - should override the toString method to a more meaning string 34