SlideShare a Scribd company logo
1 of 52
Download to read offline
Inheritance



              1
Agenda
●   What is and Why Inheritance?
●   How to derive a sub-class?
●   Object class
●   Constructor calling chain
●   “super” keyword
●   Overriding methods
●   Hiding methods
●   Hiding fields
●   Type casting
●   Final class and final methods
                                    2
What is
Inheritance?
               3
What is Inheritance?

●   Inheritance is the concept of a child class (sub class)
    automatically inheriting the variables and methods
    defined in its parent class (super class).
●   A primary feature of object-oriented programming
    along with encapsulation and polymorphism




                                                              4
Why Inheritance? Reusability
●   Benefits of Inheritance in OOP : Reusability
    –   Once a behavior (method) is defined in a super class,
        that behavior is automatically inherited by all subclasses
         ●   Thus, you write a method only once and it can be used by
             all subclasses.
    –   Once a set of properties (fields) are defined in a super
        class, the same set of properties are inherited by all
        subclasses
         ●   A class and its children share common set of properties
    –   A subclass only needs to implement the differences
        between itself and the parent.

                                                                        5
How to derive a
 sub-class?
                  6
extends keyword
●   To derive a child class, we use the extends keyword.
●   Suppose we have a parent class called Person.

    public class Person {
       protected String name;
       protected String address;

        /**
          * Default constructor
          */
        public Person(){
             System.out.println(“Inside Person:Constructor”);
             name = ""; address = "";
        }
        . . . .
    }
                                                                7
extends keyword
●    Now, we want to create another class named Student
●    Since a student is also a person, we decide to just
     extend the class Person, so that we can inherit all the
     properties and methods of the existing class Person.
●    To do this, we write,

    public class Student extends Person {
       public Student(){
          System.out.println(“Inside Student:Constructor”);
       }
       . . . .
    }

                                                              8
What You Can Do in a Sub-class
●   A subclass inherits all of the “public” and “protected”
    members (fields or methods) of its parent, no matter
    what package the subclass is in
●   If the subclass is in the same package as its parent,
    it also inherits the package-private members (fields
    or methods) of the parent




                                                              9
What You Can Do in a Sub-class
          Regarding Fields
●   The inherited fields can be used directly, just like any
    other fields.
●   You can declare new fields in the subclass that are
    not in the super class
●   You can declare a field in the subclass with the same
    name as the one in the super class, thus hiding it
    (not recommended).
●   A subclass does not inherit the private members of
    its parent class. However, if the super class has
    public or protected methods for accessing its private
    fields, these can also be used by the subclass.
                                                           10
What You Can Do in a Sub-class
         Regarding Methods
●   The inherited methods can be used directly as they are.
●   You can write a new instance method in the subclass that
    has the same signature as the one in the super class,
    thus overriding it.
●   You can write a new static method in the subclass that
    has the same signature as the one in the super class,
    thus hiding it.
●   You can declare new methods in the subclass that are
    not in the super class.



                                                              11
Object Class

               12
Object Class
●   Object class is mother of all classes
    –   In Java language, all classes are sub-classed (extended)
        from the Object super class
    –   Object class is the only class that does not have a parent
        class
●   Defines and implements behavior common to all
    classes including the ones that you write
    –   getClass()
    –   equals()
    –   toString()
    –   ...


                                                                     13
Class Hierarchy
●   A sample class hierarchy




                                 14
Super class & Sub class
●   Super class (Parent class)
    –   Any class above a specific class in the class hierarchy.
●   Sub class (Child class)
    –   Any class below a specific class in the class hierarchy.




                                                                   15
Constructor Calling
      Chain
                      16
How Constructor method of a Super
        class gets called
●   A subclass constructor invokes the constructor of
    the super class implicitly
    –   When a Student object, a subclass (child class), is
        instantiated, the default constructor of its super class
        (parent class), Person class, is invoked implicitly before
        sub-class's constructor method is invoked
●   A subclass constructor can invoke the constructor
    of the super explicitly by using the “super” keyword
    –   The constructor of the Student class can explicitly invoke
        the constructor of the Person class using “super”
        keyword
    –   Used when passing parameters to the constructor of the
        super class                                                  17
Example: Constructor Calling Chain
●   To illustrate this, consider the following code,
    public static void main( String[] args ){
       Student anna = new Student();
    }
●   In the code, we create an object of class Student.
    The output of the program is,
    Inside Person:Constructor
    Inside Student:Constructor




                                                         18
Example: Constructor Calling Chain
●   The program flow is shown below.




                                       19
“super” keyword

                  20
The “super” keyword

●   A subclass can also explicitly call a constructor of
    its immediate super class.

●   This is done by using the super constructor call.

●   A super constructor call in the constructor of a
    subclass will result in the execution of relevant
    constructor from the super class, based on the
    arguments passed.


                                                           21
The “super” keyword
●   For example, given our previous example classes
    Person and Student, we show an example of a
    super constructor call.
●   Given the following code for Student,

    public Student(){
       super( "SomeName", "SomeAddress" );
       System.out.println("Inside Student:Constructor");
    }




                                                           22
The “super” keyword
●   Few things to remember when using the super
    constructor call:
    –   The super() call must occur as the first statement in a
        constructor
    –   The super() call can only be used in a constructor (not in
        ordinary methods)




                                                                     23
The “super” keyword
●   Another use of super is to refer to members of the
    super class (just like the this reference ).
●   For example,

    public Student() {
       super.name = “somename”;
       super.address = “some address”;
    }




                                                         24
Overriding Methods

                     25
Overriding methods
●   If a derived class needs to have a different
    implementation of a certain instance method from
    that of the super class, override that instance
    method in the sub class
    –   Note that the scheme of overriding applies only to
        instance methods
    –   For static methods, it is called hiding methods
●   The overriding method has the same name,
    number and type of parameters, and return type as
    the method it overrides
●   The overriding method can also return a subtype of
    the type returned by the overridden method. This is
    called a covariant return type
                                                             26
Example: Overriding Methods
●   Suppose we have the following implementation for
    the getName method in the Person super class,
    public class Person {
       :
       :
       public String getName(){
          System.out.println("Parent: getName");
          return name;
       }
    }




                                                       27
Example: Overriding Methods
●   To override the getName method of the super class
    Person in the subclass Student, reimplement the
    method with the same signature
    public class Student extends Person{
       :
       public String getName(){
          System.out.println("Student: getName");
          return name;
       }
       :
    }
●   Now, when we invoke the getName method of an
    object of the subclass Student, the getName method of
    the Student would be called, and the output would be,
                Student: getName
                                                            28
Modifiers in the Overriding Methods
●   The access specifier for an overriding method can
    allow more, but not less, access than the overridden
    method
    –   For example, a protected instance method in the super
        class can be made public, but not private, in the subclass.
●   You will get a compile-time error if you attempt to
    change an instance method in the super class to a
    class method in the subclass, and vice versa




                                                                      29
Runtime
Polymorphism with
Overriding Methods
                     30
What is Polymorphism?

●   Polymorphism in a Java program
    –   The ability of a reference variable to change
        behavior according to what object instance it is
        holding.
    –   This allows multiple objects of different subclasses
        to be treated as objects of a single super class,
        while automatically selecting the proper methods to
        apply to a particular object based on the subclass it
        belongs to
    –   (We will talk more on Polymorphism during our
        Polymorphism presentation.)

                                                                31
Example: Runtime Polymorphism

Code:

     Person person2 = new Student();
     person2.myMethod("test4");

     Person person3 = new InternationalStudent();
     person3.myMethod("test5");

Result:

  myMethod(test4) in Student class is called
  myMethod(test5) in InternationalStudent class is called
                                                      32
Hiding Methods

                 33
Hiding Methods
●   If a subclass defines a class method (static method)
    with the same signature as a class method in the
    super class, the method in the subclass “hides” the
    one in the super class




                                                           34
Example: Coding of Hiding Static
           Method
class Animal {
   public static void testClassMethod() {
     System.out.println("The class method in Animal.");
   }
}

// The testClassMethod() of the child class hides the one of the
// super class – it looks like overriding, doesn't it? But
// there is difference. We will talk about in the following slide.

class Cat extends Animal {
   public static void testClassMethod() {
     System.out.println("The class method in Cat.");
   }
                                                                35
}
Overriding Method vs. Hiding Method
 ●   Hiding a static method of a super class looks like
     overriding an instance method of a super class
 ●   The difference comes during runtime
     –   When you override an instance method, you get the benefit
         of run-time polymorphism
     –   When you override an static method, there is no runt-time
         polymorphism




                                                                     36
Example: Overriding Method vs. Hiding
      Method during Runtime
    // Create object instance of Cat.
    Cat myCat = new Cat();

    // The object instance is Cat type
    // and assigned to Animal type variable.
    Animal myAnimal2 = myCat;

    // For static method, the static method of
    // the super class gets called.
    Animal.testClassMethod();

    // For instance method, the instance method
    // of the subclass is called even though
    // myAnimal2 is a super class type. This is
    // run-time polymorphism.
    myAnimal2.testInstanceMethod();
                                                  37
Hiding Fields

                38
Hiding Fields
●   Within a sub class, a field that has the same name as
    a field in the super class hides the super class' field,
    even if their types are different
●   Within the subclass, the field in the super class
    cannot be referenced by its simple name
    –   Instead, the field must be accessed through super keyword
●   Generally speaking, hiding fields is not a
    recommended programming practice as it makes
    code difficult to read


                                                                39
Type Casting

               40
What is “Type”?
●   When an object instance is created from a class, we
    say the object instance is “type” of the class and its
    super classes
●   Example:
         Student student1 = new Student();
    –   student1 object instance is the type of Student or it is
        Student type
    –   student1 object instance is also type of Person if Student is
        a child class of Person
    –   student1 object instance is also type of Object


                                                                    41
What is Significance?
●   An object instance of a particular type can be used in
    any place where an instance of the type and its super
    type is called for
●   Example:
    –   student1 object instance is a “type” of TuftsStudent,
        Student, and Peson
    –   student1 object can be used in any place where object
        instance of the type of TuftsStudent, Student, or Person is
        called for
●   This enables polymorphism

                                                                      42
Implicit Type Casting
●   An object instance of a subclass can be assigned to a
    variable (reference) of a parent class through implicit
    type casting – this is safe since an object instance of a
    subclass “is” also the type of the super class
●   Example
     –   Let's assume Student class is a child class of Person class
     –   Let's assume TuftsStudent class is a child class of Student
         class
     TuftsStudent tuftstudent = new TuftsStudent();
     Student student = tuftsstudent; // Implicit type casting
     Person person = tuftsstudent; // Implicit type casting
     Object object = tuftsstudent; // Implicit type casting
                                                                       43
Type Casting between Objects


tuftsstudent


  student          TuftsStudent
                 Object instance

  person




                                   44
Explicit Type Casting
●   An object instance of a super class must be assigned to
    a variable (reference) of a child class through explicit
    type casting
    –   Not doing it will result in a compile error since the type
        assignment is not safe
    –   Compiler wants to make sure you know what you are doing
●   Example
    –   Let's assume Student class is a child class of Person class
    Person person1 = new Student();
    Student student1 = (Student) person1; // Explicit type casting


                                                                     45
Runtime Type Mismatch Exception
●   Even with explicit casting, you could still end up
    having a runtime error
●   Example
    –   Let's assume Student class is a child class of Person class
    –   Let's assume Teacher class is also a child class of Person
        class
    Person person1 = new Student();
    Person person2 = new Teacher();
    Student student1 = (Student) person1; // Explicit type casting
    // No compile error, but runtime type mismatch exception
    Student student2 = (Student) person2;
                                                                     46
Use instanceof Operator to
Prevent Runtime Type Mismatch Error
 ●   You can check the type of the object instance using
     instanceof before the type casting
 ●   Example
     Person person1 = new Student();
     Person person2 = new Teacher();


     // Do the casting only when the type is verified
     if (person2 instanceof Student) {
         Student student2 = (Student) person2;
     }

                                                           47
Final Class &
Final Method
                48
Final Classes
●   Final Classes
    –   Classes that cannot be extended
    –   To declare final classes, we write,
           public final ClassName{
              . . .
           }
●   Example:
          public final class Person {
             . . .
          }

●   Other examples of final classes are your wrapper
    classes and String class
    –   You cannot create a subclass of String class   49
Final Methods
●   Final Methods
    –   Methods that cannot be overridden
    –   To declare final methods, we write,
           public final [returnType] [methodName]([parameters]){
              . . .
           }
●
    Static methods are automatically final




                                                               50
Example: final Methods
public final String getName(){
   return name;
}




                                 51
Inheritance



              52

More Related Content

What's hot

Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In JavaMD SALEEM QAISAR
 
Java Inheritance | Java Course
Java Inheritance | Java Course Java Inheritance | Java Course
Java Inheritance | Java Course RAKESH P
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in javaAtul Sehdev
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in JavaKurapati Vishwak
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 
Seminar on java
Seminar on javaSeminar on java
Seminar on javashathika
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance pptNivegeetha
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerTOPS Technologies
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: InheritanceTareq Hasan
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and PolymorphismKartikKapgate
 
Inheritance polymorphism-in-java
Inheritance polymorphism-in-javaInheritance polymorphism-in-java
Inheritance polymorphism-in-javaDeepak Singh
 
Java Inheritance
Java InheritanceJava Inheritance
Java InheritanceVINOTH R
 

What's hot (20)

Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
 
Java Inheritance | Java Course
Java Inheritance | Java Course Java Inheritance | Java Course
Java Inheritance | Java Course
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Java
JavaJava
Java
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java(inheritance)
Java(inheritance)Java(inheritance)
Java(inheritance)
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance ppt
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Inheritance polymorphism-in-java
Inheritance polymorphism-in-javaInheritance polymorphism-in-java
Inheritance polymorphism-in-java
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 

Viewers also liked

Viewers also liked (8)

2015 ii - listado de cursos dac - áreas junio 30 (1)
2015 ii - listado de cursos dac - áreas junio 30 (1)2015 ii - listado de cursos dac - áreas junio 30 (1)
2015 ii - listado de cursos dac - áreas junio 30 (1)
 
AWTEventModel
AWTEventModelAWTEventModel
AWTEventModel
 
struts
strutsstruts
struts
 
Presosutra
PresosutraPresosutra
Presosutra
 
Jan Lok Pal
Jan Lok PalJan Lok Pal
Jan Lok Pal
 
javaarray
javaarrayjavaarray
javaarray
 
javanetworking
javanetworkingjavanetworking
javanetworking
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 

Similar to javainheritance

Similar to javainheritance (20)

Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
04inherit
04inherit04inherit
04inherit
 
Javapolymorphism
JavapolymorphismJavapolymorphism
Javapolymorphism
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Python_Unit_3.pdf
Python_Unit_3.pdfPython_Unit_3.pdf
Python_Unit_3.pdf
 
Oops
OopsOops
Oops
 
OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extra
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
 
Oops and enums
Oops and enumsOops and enums
Oops and enums
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثة
 

More from Arjun Shanka (20)

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82
 
javarmi
javarmijavarmi
javarmi
 
hibernate
hibernatehibernate
hibernate
 
javapackage
javapackagejavapackage
javapackage
 
swingbasics
swingbasicsswingbasics
swingbasics
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
javathreads
javathreadsjavathreads
javathreads
 
javabeans
javabeansjavabeans
javabeans
 
72185-26528-StrutsMVC
72185-26528-StrutsMVC72185-26528-StrutsMVC
72185-26528-StrutsMVC
 
javaiostream
javaiostreamjavaiostream
javaiostream
 
servlets
servletsservlets
servlets
 
slides6
slides6slides6
slides6
 
06-Event-Handlingadvansed
06-Event-Handlingadvansed06-Event-Handlingadvansed
06-Event-Handlingadvansed
 
Java_Comb
Java_CombJava_Comb
Java_Comb
 
Java-Events
Java-EventsJava-Events
Java-Events
 
javainterface
javainterfacejavainterface
javainterface
 

Recently uploaded

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

javainheritance

  • 2. Agenda ● What is and Why Inheritance? ● How to derive a sub-class? ● Object class ● Constructor calling chain ● “super” keyword ● Overriding methods ● Hiding methods ● Hiding fields ● Type casting ● Final class and final methods 2
  • 4. What is Inheritance? ● Inheritance is the concept of a child class (sub class) automatically inheriting the variables and methods defined in its parent class (super class). ● A primary feature of object-oriented programming along with encapsulation and polymorphism 4
  • 5. Why Inheritance? Reusability ● Benefits of Inheritance in OOP : Reusability – Once a behavior (method) is defined in a super class, that behavior is automatically inherited by all subclasses ● Thus, you write a method only once and it can be used by all subclasses. – Once a set of properties (fields) are defined in a super class, the same set of properties are inherited by all subclasses ● A class and its children share common set of properties – A subclass only needs to implement the differences between itself and the parent. 5
  • 6. How to derive a sub-class? 6
  • 7. extends keyword ● To derive a child class, we use the extends keyword. ● Suppose we have a parent class called Person. public class Person { protected String name; protected String address; /** * Default constructor */ public Person(){ System.out.println(“Inside Person:Constructor”); name = ""; address = ""; } . . . . } 7
  • 8. extends keyword ● Now, we want to create another class named Student ● Since a student is also a person, we decide to just extend the class Person, so that we can inherit all the properties and methods of the existing class Person. ● To do this, we write, public class Student extends Person { public Student(){ System.out.println(“Inside Student:Constructor”); } . . . . } 8
  • 9. What You Can Do in a Sub-class ● A subclass inherits all of the “public” and “protected” members (fields or methods) of its parent, no matter what package the subclass is in ● If the subclass is in the same package as its parent, it also inherits the package-private members (fields or methods) of the parent 9
  • 10. What You Can Do in a Sub-class Regarding Fields ● The inherited fields can be used directly, just like any other fields. ● You can declare new fields in the subclass that are not in the super class ● You can declare a field in the subclass with the same name as the one in the super class, thus hiding it (not recommended). ● A subclass does not inherit the private members of its parent class. However, if the super class has public or protected methods for accessing its private fields, these can also be used by the subclass. 10
  • 11. What You Can Do in a Sub-class Regarding Methods ● The inherited methods can be used directly as they are. ● You can write a new instance method in the subclass that has the same signature as the one in the super class, thus overriding it. ● You can write a new static method in the subclass that has the same signature as the one in the super class, thus hiding it. ● You can declare new methods in the subclass that are not in the super class. 11
  • 13. Object Class ● Object class is mother of all classes – In Java language, all classes are sub-classed (extended) from the Object super class – Object class is the only class that does not have a parent class ● Defines and implements behavior common to all classes including the ones that you write – getClass() – equals() – toString() – ... 13
  • 14. Class Hierarchy ● A sample class hierarchy 14
  • 15. Super class & Sub class ● Super class (Parent class) – Any class above a specific class in the class hierarchy. ● Sub class (Child class) – Any class below a specific class in the class hierarchy. 15
  • 17. How Constructor method of a Super class gets called ● A subclass constructor invokes the constructor of the super class implicitly – When a Student object, a subclass (child class), is instantiated, the default constructor of its super class (parent class), Person class, is invoked implicitly before sub-class's constructor method is invoked ● A subclass constructor can invoke the constructor of the super explicitly by using the “super” keyword – The constructor of the Student class can explicitly invoke the constructor of the Person class using “super” keyword – Used when passing parameters to the constructor of the super class 17
  • 18. Example: Constructor Calling Chain ● To illustrate this, consider the following code, public static void main( String[] args ){ Student anna = new Student(); } ● In the code, we create an object of class Student. The output of the program is, Inside Person:Constructor Inside Student:Constructor 18
  • 19. Example: Constructor Calling Chain ● The program flow is shown below. 19
  • 21. The “super” keyword ● A subclass can also explicitly call a constructor of its immediate super class. ● This is done by using the super constructor call. ● A super constructor call in the constructor of a subclass will result in the execution of relevant constructor from the super class, based on the arguments passed. 21
  • 22. The “super” keyword ● For example, given our previous example classes Person and Student, we show an example of a super constructor call. ● Given the following code for Student, public Student(){ super( "SomeName", "SomeAddress" ); System.out.println("Inside Student:Constructor"); } 22
  • 23. The “super” keyword ● Few things to remember when using the super constructor call: – The super() call must occur as the first statement in a constructor – The super() call can only be used in a constructor (not in ordinary methods) 23
  • 24. The “super” keyword ● Another use of super is to refer to members of the super class (just like the this reference ). ● For example, public Student() { super.name = “somename”; super.address = “some address”; } 24
  • 26. Overriding methods ● If a derived class needs to have a different implementation of a certain instance method from that of the super class, override that instance method in the sub class – Note that the scheme of overriding applies only to instance methods – For static methods, it is called hiding methods ● The overriding method has the same name, number and type of parameters, and return type as the method it overrides ● The overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type 26
  • 27. Example: Overriding Methods ● Suppose we have the following implementation for the getName method in the Person super class, public class Person { : : public String getName(){ System.out.println("Parent: getName"); return name; } } 27
  • 28. Example: Overriding Methods ● To override the getName method of the super class Person in the subclass Student, reimplement the method with the same signature public class Student extends Person{ : public String getName(){ System.out.println("Student: getName"); return name; } : } ● Now, when we invoke the getName method of an object of the subclass Student, the getName method of the Student would be called, and the output would be, Student: getName 28
  • 29. Modifiers in the Overriding Methods ● The access specifier for an overriding method can allow more, but not less, access than the overridden method – For example, a protected instance method in the super class can be made public, but not private, in the subclass. ● You will get a compile-time error if you attempt to change an instance method in the super class to a class method in the subclass, and vice versa 29
  • 31. What is Polymorphism? ● Polymorphism in a Java program – The ability of a reference variable to change behavior according to what object instance it is holding. – This allows multiple objects of different subclasses to be treated as objects of a single super class, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to – (We will talk more on Polymorphism during our Polymorphism presentation.) 31
  • 32. Example: Runtime Polymorphism Code: Person person2 = new Student(); person2.myMethod("test4"); Person person3 = new InternationalStudent(); person3.myMethod("test5"); Result: myMethod(test4) in Student class is called myMethod(test5) in InternationalStudent class is called 32
  • 34. Hiding Methods ● If a subclass defines a class method (static method) with the same signature as a class method in the super class, the method in the subclass “hides” the one in the super class 34
  • 35. Example: Coding of Hiding Static Method class Animal { public static void testClassMethod() { System.out.println("The class method in Animal."); } } // The testClassMethod() of the child class hides the one of the // super class – it looks like overriding, doesn't it? But // there is difference. We will talk about in the following slide. class Cat extends Animal { public static void testClassMethod() { System.out.println("The class method in Cat."); } 35 }
  • 36. Overriding Method vs. Hiding Method ● Hiding a static method of a super class looks like overriding an instance method of a super class ● The difference comes during runtime – When you override an instance method, you get the benefit of run-time polymorphism – When you override an static method, there is no runt-time polymorphism 36
  • 37. Example: Overriding Method vs. Hiding Method during Runtime // Create object instance of Cat. Cat myCat = new Cat(); // The object instance is Cat type // and assigned to Animal type variable. Animal myAnimal2 = myCat; // For static method, the static method of // the super class gets called. Animal.testClassMethod(); // For instance method, the instance method // of the subclass is called even though // myAnimal2 is a super class type. This is // run-time polymorphism. myAnimal2.testInstanceMethod(); 37
  • 39. Hiding Fields ● Within a sub class, a field that has the same name as a field in the super class hides the super class' field, even if their types are different ● Within the subclass, the field in the super class cannot be referenced by its simple name – Instead, the field must be accessed through super keyword ● Generally speaking, hiding fields is not a recommended programming practice as it makes code difficult to read 39
  • 41. What is “Type”? ● When an object instance is created from a class, we say the object instance is “type” of the class and its super classes ● Example: Student student1 = new Student(); – student1 object instance is the type of Student or it is Student type – student1 object instance is also type of Person if Student is a child class of Person – student1 object instance is also type of Object 41
  • 42. What is Significance? ● An object instance of a particular type can be used in any place where an instance of the type and its super type is called for ● Example: – student1 object instance is a “type” of TuftsStudent, Student, and Peson – student1 object can be used in any place where object instance of the type of TuftsStudent, Student, or Person is called for ● This enables polymorphism 42
  • 43. Implicit Type Casting ● An object instance of a subclass can be assigned to a variable (reference) of a parent class through implicit type casting – this is safe since an object instance of a subclass “is” also the type of the super class ● Example – Let's assume Student class is a child class of Person class – Let's assume TuftsStudent class is a child class of Student class TuftsStudent tuftstudent = new TuftsStudent(); Student student = tuftsstudent; // Implicit type casting Person person = tuftsstudent; // Implicit type casting Object object = tuftsstudent; // Implicit type casting 43
  • 44. Type Casting between Objects tuftsstudent student TuftsStudent Object instance person 44
  • 45. Explicit Type Casting ● An object instance of a super class must be assigned to a variable (reference) of a child class through explicit type casting – Not doing it will result in a compile error since the type assignment is not safe – Compiler wants to make sure you know what you are doing ● Example – Let's assume Student class is a child class of Person class Person person1 = new Student(); Student student1 = (Student) person1; // Explicit type casting 45
  • 46. Runtime Type Mismatch Exception ● Even with explicit casting, you could still end up having a runtime error ● Example – Let's assume Student class is a child class of Person class – Let's assume Teacher class is also a child class of Person class Person person1 = new Student(); Person person2 = new Teacher(); Student student1 = (Student) person1; // Explicit type casting // No compile error, but runtime type mismatch exception Student student2 = (Student) person2; 46
  • 47. Use instanceof Operator to Prevent Runtime Type Mismatch Error ● You can check the type of the object instance using instanceof before the type casting ● Example Person person1 = new Student(); Person person2 = new Teacher(); // Do the casting only when the type is verified if (person2 instanceof Student) { Student student2 = (Student) person2; } 47
  • 48. Final Class & Final Method 48
  • 49. Final Classes ● Final Classes – Classes that cannot be extended – To declare final classes, we write, public final ClassName{ . . . } ● Example: public final class Person { . . . } ● Other examples of final classes are your wrapper classes and String class – You cannot create a subclass of String class 49
  • 50. Final Methods ● Final Methods – Methods that cannot be overridden – To declare final methods, we write, public final [returnType] [methodName]([parameters]){ . . . } ● Static methods are automatically final 50
  • 51. Example: final Methods public final String getName(){ return name; } 51