j12 inheritance

Upload: eragol

Post on 30-May-2018

237 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 J12 Inheritance

    1/52

    1

    J12 InheritanceJ12 Inheritance

  • 8/14/2019 J12 Inheritance

    2/52

    2

    Agenda

    What is and Why Inheritance? How to derive a sub-class?

    Object class

    Constructor calling chain super keyword

    Overriding methods (most important)

    Hiding methods

    Hiding fields

    Type casting

    Final class and final methods

  • 8/14/2019 J12 Inheritance

    3/52

    3

    What isWhat isInheritance?Inheritance?

  • 8/14/2019 J12 Inheritance

    4/52

    4

    What is Inheritance?

    Inheritance is the concept of a child class (sub class)automatically inheriting the variables and methodsdefined in its parent class (super class).

    A primary feature of object-oriented programmingalong with encapsulation and polymorphism

  • 8/14/2019 J12 Inheritance

    5/52

    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 byall subclasses.

    Once a set of properties (fields) are defined in a superclass, the same set of properties are inherited by allsubclasses

    A class and its children share common set of properties

    A subclass only needs to implement the differencesbetween itself and the parent.

  • 8/14/2019 J12 Inheritance

    6/526

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

  • 8/14/2019 J12 Inheritance

    7/52

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

    }. . . .

    }

  • 8/14/2019 J12 Inheritance

    8/52

    8

    extends keyword

    Now, we want to create another class named Student

    Since a student is also a person, we decide to justextend 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/14/2019 J12 Inheritance

    9/52

    9

    What You Can Do in a Sub-class

    A subclass inherits all of the public and protectedmembers (fields or methods) of its parent, no matterwhat package the subclass is in

    If the subclass is in the same package as its parent,it also inherits the package-private members (fieldsor methods) of the parent

  • 8/14/2019 J12 Inheritance

    10/52

    10

    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).

    A subclass does not inherit the private members of itsparent class. However, if the super class has publicor protected methods for accessing its private fields,these can also be used by the subclass.

  • 8/14/2019 J12 Inheritance

    11/52

    11

    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.

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

  • 8/14/2019 J12 Inheritance

    12/52

    12

    Object ClassObject Class

  • 8/14/2019 J12 Inheritance

    13/52

    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 parentclass

    Defines and implements behavior common to allclasses including the ones that you write

    getClass()

    equals()

    toString()

    ...

  • 8/14/2019 J12 Inheritance

    14/52

    14

    Class Hierarchy

    A sample class hierarchy

  • 8/14/2019 J12 Inheritance

    15/52

    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.

  • 8/14/2019 J12 Inheritance

    16/52

    16

    Constructor CallingConstructor CallingChainChain

  • 8/14/2019 J12 Inheritance

    17/52

    17

    How Constructor method of a Superclass gets 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/14/2019 J12 Inheritance

    18/52

    18

    Example: Constructor Calling Chain

    To illustrate this, consider the following code,

    In the code, we create an object of class Student.The output of the program is,

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

    }

    Inside Person:Constructor

    Inside Student:Constructor

  • 8/14/2019 J12 Inheritance

    19/52

    19

    Example: Constructor Calling Chain

    The program flow is shown below.

  • 8/14/2019 J12 Inheritance

    20/52

    20

    super keywordsuper keyword

  • 8/14/2019 J12 Inheritance

    21/52

    21

    The super keyword

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

    This is done by using the superconstructor call.

    A superconstructor call in the constructor of asubclass will result in the execution of relevant

    constructor from the super class, based on thearguments passed.

  • 8/14/2019 J12 Inheritance

    22/52

    22

    The super keyword

    For example, given our previous example classesPerson and Student, we show an example of asuper constructor call.

    Given the following code for Student,

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

    }

  • 8/14/2019 J12 Inheritance

    23/52

    23

    The super keyword

    Few things to remember when using the superconstructor 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/14/2019 J12 Inheritance

    24/52

    24

    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/14/2019 J12 Inheritance

    25/52

    25

    Overriding MethodsOverriding Methods

  • 8/14/2019 J12 Inheritance

    26/52

    26

    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 toinstance methods

    For static methods, it is called hiding methods

    The overriding method has the same name,number and type of parameters, and return type asthe method it overrides

    The overriding method can also return a subtype ofthe type returned by the overridden method. This iscalled a covariant return type

  • 8/14/2019 J12 Inheritance

    27/52

    27

    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/14/2019 J12 Inheritance

    28/52

    28

    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 an objectof the subclass Student, the getName method of theStudent 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/14/2019 J12 Inheritance

    29/52

    29

    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 a

    class method in the subclass, and vice versa

  • 8/14/2019 J12 Inheritance

    30/52

    30

    RuntimeRuntime

    Polymorphism withPolymorphism withOverriding MethodsOverriding Methods

  • 8/14/2019 J12 Inheritance

    31/52

    31

    What is Polymorphism?

    Polymorphism in a Java program

    The ability of a reference variable to changebehavior 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 toapply to a particular object based on the subclass itbelongs to

    (We will talk more on Polymorphism during ourPolymorphism presentation.)

  • 8/14/2019 J12 Inheritance

    32/52

    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 calledmyMethod(test5) in InternationalStudent class is called

  • 8/14/2019 J12 Inheritance

    33/52

    33

    Hiding MethodsHiding Methods

  • 8/14/2019 J12 Inheritance

    34/52

    34

    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 the

    one in the super class

  • 8/14/2019 J12 Inheritance

    35/52

    35

    Example: Coding of Hiding StaticMethod

    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/14/2019 J12 Inheritance

    36/52

    36

    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

    E l O idi M th d Hidi

  • 8/14/2019 J12 Inheritance

    37/52

    37

    Example: Overriding Method vs. HidingMethod 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();

  • 8/14/2019 J12 Inheritance

    38/52

    38

    Hiding FieldsHiding Fields

  • 8/14/2019 J12 Inheritance

    39/52

    39

    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/14/2019 J12 Inheritance

    40/52

    40

    Type CastingType Casting

  • 8/14/2019 J12 Inheritance

    41/52

    41

    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/14/2019 J12 Inheritance

    42/52

    42

    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 TuftsStudent,

    Student, and Peson

    student1 object can be used in any place where object

    instance of the type of TuftsStudent, Student, or Person iscalled for

    This enables polymorphism

  • 8/14/2019 J12 Inheritance

    43/52

  • 8/14/2019 J12 Inheritance

    44/52

    44

    Type Casting between Objects

    tuftsstudent

    student

    person

    TuftsStudentObject instance

  • 8/14/2019 J12 Inheritance

    45/52

    45

    Explicit Type Casting

    An object instance of a super class must be assigned toa variable (reference) of a child class through explicittype casting

    Not doing it will result in a compile error since the typeassignment is not safe

    Compiler wants to make sure you know what you are doing

    Example

    Let's assume Student class is a child class ofPerson classPerson person1 = new Student();

    Student student1 = (Student) person1; // Explicit type casting

  • 8/14/2019 J12 Inheritance

    46/52

    46

    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;

    Use instanceof Operator to

  • 8/14/2019 J12 Inheritance

    47/52

    47

    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;

    }

  • 8/14/2019 J12 Inheritance

    48/52

    48

    Final Class &Final Class &Final MethodFinal Method

  • 8/14/2019 J12 Inheritance

    49/52

    49

    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/14/2019 J12 Inheritance

    50/52

    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

  • 8/14/2019 J12 Inheritance

    51/52

    51

    Example: final Methods

    public final String getName(){return name;

    }

  • 8/14/2019 J12 Inheritance

    52/52

    52

    InheritanceInheritance