Javase Inheritance

Embed Size (px)

Citation preview

  • 8/2/2019 Javase Inheritance

    1/49

    1

    InheritanceInheritance(Importance scale: ****,(Importance scale: ****,

    Very important)Very important)

    Sang ShinSang ShinMichle GarocheMichle Garoche

    www.javapassion.comwww.javapassion.comLearn with Passion!Learn with Passion!

    1

  • 8/2/2019 Javase Inheritance

    2/49

    2

    Agenda

    What is and Why Inheritance? Objectclass

    How to derive a sub-class?

    Constructor calling chain

    super keyword

    Overriding methods

    Hiding methods (not important, skip if you want)

    Hiding fields (not important, skip if you want))

    Type casting (very important)

    Final class and final methods

  • 8/2/2019 Javase Inheritance

    3/49

    3

    What isWhat isInheritance?Inheritance?

  • 8/2/2019 Javase Inheritance

    4/49

    4

    What is Inheritance?

    Inheritance is the concept of a child classautomatically inheriting the variables and methodsdefined in its parent class

    Parent class is the same thing as super class Child class is the same thing as sub class

    A primary feature of object-oriented programming

    Along with encapsulation and polymorphism

  • 8/2/2019 Javase Inheritance

    5/49

    5

    Why Inheritance? Reusability

    Once a behavior (method) is defined in a superclass, that behavior is automatically inherited by allsubclasses

    Thus, you write a method only once and it can be usedby all subclasses.

    Once a set of properties (fields) are defined in asuper 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 differencesbetween itself and the parent.

  • 8/2/2019 Javase Inheritance

    6/496

    Object ClassObject Class

  • 8/2/2019 Javase Inheritance

    7/49

    7

    ObjectClass

    Object class is mother of all classes

    In Java language, all classes are subclassed (extended)from the Objectsuper class

    Object class is the only class that does not have a parent

    class

    Defines and implements behavior common to allclasses

    getClass()

    equals()

    toString()

    ...

  • 8/2/2019 Javase Inheritance

    8/49

  • 8/2/2019 Javase Inheritance

    9/49

    9

    How to derive aHow to derive asub-class?sub-class?

  • 8/2/2019 Javase Inheritance

    10/49

    10

    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 = "";

    }

    . . . .

    }

  • 8/2/2019 Javase Inheritance

    11/49

  • 8/2/2019 Javase Inheritance

    12/49

  • 8/2/2019 Javase Inheritance

    13/49

    13

    What You Can Do in a Sub-classRegarding Fields

    The inherited fields can be used directly, just like anyother 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 and rarely used)

    A subclass does not inherit the private members ofits parent class. However, if the super class haspublic or protected methods for accessing its privatefields, these can also be used by the subclass.

  • 8/2/2019 Javase Inheritance

    14/49

    14

    What You Can Do in a Sub-classRegarding Methods

    The inherited methods can be used directly as they are.

    You can write a new instance method in the subclass thathas 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. (not recommended and rarely used)

    You can declare new methods in the subclass that arenot in the super class.

  • 8/2/2019 Javase Inheritance

    15/49

    15

    Constructor CallingConstructor CallingChainChain

  • 8/2/2019 Javase Inheritance

    16/49

    16

    How Constructor method of a Super classgets called

    A subclass constructor invokes the constructor ofthe 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 beforesub-class's constructor method is invoked

    A subclass constructor can invoke the constructorof the super explicitly by using the super keyword

    The constructor of the Student class can explicitly invokethe constructor of the Person class using superkeyword

    Used when passing parameters to the constructor of the

    super class

  • 8/2/2019 Javase Inheritance

    17/49

    17

    Example: Constructor Calling Chain

    Person class

    public class Person {public Person() {

    System.out.println("Person: constructor is called");}..

    Student class

    public class Student extends Person {public Student() {

    System.out.println("Student: constructor is called");}...

    Main class

    public static void main( String[] args ){Student anna = new Student();

    }

    ResultPerson: constructor is called

    Student: constructor is called

  • 8/2/2019 Javase Inheritance

    18/49

    18

    Example: Constructor Calling Chain

    The program flow is shown below.

  • 8/2/2019 Javase Inheritance

    19/49

    19

    super keywordsuper keyword

  • 8/2/2019 Javase Inheritance

    20/49

    20

    The super keyword

    A subclass can also explicitly call a constructor ofits immediate super class.

    This is in replacement of the default behavior of the

    constructor call chaining This is done by using the super(..) constructor call.

    A super(..) constructor call in the constructor of asubclass will result in the execution of relevant

    constructor from the super class, based on thearguments passed.

  • 8/2/2019 Javase Inheritance

    21/49

    21

    Explicit calling super(..)

    public class Person {

    public Person() {System.out.println("Person: constructor is called");

    }

    public Person(String name) {

    this.name = name;

    System.out.println("Person: constructor 2 is called");

    }

    }

    public class Student extends Person {

    public Student() {

    System.out.println("Student: constructor is called");

    }

    public Student(String name, String school, double grade) { super(name);

    this.school = school;

    this.grade = grade;

    System.out.println("Student: constructor 2 is called");

    }

    ..

  • 8/2/2019 Javase Inheritance

    22/49

    22

    The super keyword

    A couple of things to remember when using thesuper 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)

  • 8/2/2019 Javase Inheritance

    23/49

    23

    The super keyword

    Another use of super is to refer to members of thesuper class (just like the this reference ).

    For example,

    public Student() {

    super.name = somename;

    super.address = some address;

    }

  • 8/2/2019 Javase Inheritance

    24/49

    24

    Overriding MethodsOverriding Methods

  • 8/2/2019 Javase Inheritance

    25/49

    25

    Overriding methods

    If a derived class needs to have a differentimplementation of a certain instance method fromthat of the super class, override that instancemethod 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 iscalled a covariant return type

  • 8/2/2019 Javase Inheritance

    26/49

    26

    Example: Overriding Methods

    Suppose we have the following implementation forthe getName method in the Person super class,

    public class Person {

    ::

    public String getName(){

    System.out.println("Parent: getName");

    return name;

    }

    }

  • 8/2/2019 Javase Inheritance

    27/49

    27

    Example: Overriding Methods

    To override the getName method of the super classPerson in the subclass Student, reimplement themethod with the same signature

    Now, when we invoke the getName method of anobject of the subclass Student, the getName method ofthe Student would be called, and the output would be,

    public class Student extends Person{

    :

    public String getName(){

    System.out.println("Student: getName");

    return name;

    }

    :

    }

    Student: getName

  • 8/2/2019 Javase Inheritance

    28/49

    28

    Modifiers in the Overriding Methods

    The access specifier for an overriding method canallow more, but not less, access than the overriddenmethod

    For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

    You will get a compile-time error if you attempt tochange an instance method in the super class to aclass method in the subclass, and vice versa

  • 8/2/2019 Javase Inheritance

    29/49

    29

    Hiding MethodsHiding Methods

  • 8/2/2019 Javase Inheritance

    30/49

    30

    Hiding Methods

    If a subclass defines a class method (static method)with the same signature as a class method in thesuper class, the method in the subclass hides theone in the super class

  • 8/2/2019 Javase Inheritance

    31/49

    31

    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.");}

    }

  • 8/2/2019 Javase Inheritance

    32/49

    32

    Overriding Method vs. Hiding Method

    Hiding a static method of a super class looks likeoverriding an instance method of a super class

    The difference comes during runtime

    When you override an instance method, you get the benefitof run-time polymorphism

    When you override an static method, there is no runt-timepolymorphism

  • 8/2/2019 Javase Inheritance

    33/49

  • 8/2/2019 Javase Inheritance

    34/49

    34

    Hiding FieldsHiding Fields

  • 8/2/2019 Javase Inheritance

    35/49

    35

    Hiding Fields

    Within a sub class, a field that has the same name asa field in the super class hides the super class' field,even if their types are different

    Within the subclass, the field in the super classcannot be referenced by its simple name

    Instead, the field must be accessed through superkeyword

    Generally speaking, hiding fields is not a

    recommended programming practice as it makescode difficult to read

  • 8/2/2019 Javase Inheritance

    36/49

    36

    Type CastingType Casting(This is very important concept.)(This is very important concept.)

  • 8/2/2019 Javase Inheritance

    37/49

    37

    What is Type?

    When an object instance is created from a class, wesay the object instance is type of the class and itssuper classes

    Example:Student student1 = new Student();

    student1 object instance is the type of Student or it isStudent type

    student1 object instance is also type of Person if Student isa child class of Person

    student1 object instance is also type of Object

  • 8/2/2019 Javase Inheritance

    38/49

    38

    What is Significance?

    An object instance of a particular type can be used inany place where an instance of the type and its supertype is called for

    Example: student1 object instance is a type of JavaStudent,

    Student, and Person

    student1 object can be used in any place where objectinstance of the type of JavaStudent, Student, or Person iscalled for

    This enables polymorphism

  • 8/2/2019 Javase Inheritance

    39/49

    39

    Implicit Type Casting (Very Important)

    An object instance of a subclass can be assigned to avariable (reference) of a parent class through implicittype casting this is safe since an object instance of asubclass is also the type of the super class

    Example

    Let's assume Student class is a child class ofPerson class

    Let's assume JavaStudent class is a child class ofStudentclass

    JavaStudent javaStudent = new JavaStudent();

    Student student = javaStudent; // Implicit type casting

    Person person = javaStudent; // Implicit type casting

    Object object = javaStudent; // Implicit type casting

  • 8/2/2019 Javase Inheritance

    40/49

  • 8/2/2019 Javase Inheritance

    41/49

  • 8/2/2019 Javase Inheritance

    42/49

    42

    Runtime Type Mismatch Exception

    Even with explicit casting, you could still end uphaving a runtime error

    Example

    Let's assume Student class is a child class ofPerson class Let's assume Teacherclass is also a child class ofPerson

    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;

  • 8/2/2019 Javase Inheritance

    43/49

    43

    Use instanceof Operator toPrevent Runtime Type Mismatch Error

    You can check the type of the object instance usinginstanceofbefore 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;

    }

    B U G i d T

  • 8/2/2019 Javase Inheritance

    44/49

    44

    Better Use Generics to detect TypeMismatch problem during Compile time

    Generics is introduced from Java SE 5

    Generics is designed to detect Type mismatchproblem during compile time not during runtime

  • 8/2/2019 Javase Inheritance

    45/49

    45

    Final Class &Final Class &Final MethodFinal Method

  • 8/2/2019 Javase Inheritance

    46/49

    46

    Final Classes

    Final Classes Classes that cannot be extended

    To declare final classes, we write,public final ClassName{

    . . .}

    Example:

    Other examples of final classes are your wrapperclasses and String class

    You cannot create a subclass of String class

    public final class Person {

    . . .

    }

  • 8/2/2019 Javase Inheritance

    47/49

    47

    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

  • 8/2/2019 Javase Inheritance

    48/49

    48

    Example: final Methods

    public final String getName(){

    return name;

    }

  • 8/2/2019 Javase Inheritance

    49/49

    48

    Thank you!Thank you!

    Check JavaPassion.com Codecamps!Check JavaPassion.com Codecamps!http://www.javapassion.com/codecampshttp://www.javapassion.com/codecampsLearn with Passion!Learn with Passion!

    49

    http://www.javapassion.com/codecampshttp://www.javapassion.com/codecampshttp://www.javapassion.com/codecamps