Ch05 Inheritance

Embed Size (px)

Citation preview

  • 8/6/2019 Ch05 Inheritance

    1/51

    INHERITANCE

  • 8/6/2019 Ch05 Inheritance

    2/51

    Concept Inheritance is based on the idea ofreusability.

    This means that the features of an existingclass are reused and new features are added

    to it.

    The existing class undergoes no modifications(i.e. it remains unchanged), it is just extended

    to form a new class. As a result, the new class has combined

    features of both the classes.

  • 8/6/2019 Ch05 Inheritance

    3/51

    C

    Functions

    Pointers

    CPlusPlus

    Exten

    d

    Existing Class

    New Class

    Functions

    PointersAbstraction

    Encapsulation

    Overloading

    Reused Part

    New Part

    Super/Base/Parent

    Class

    Sub/Derived/Chil

    Class

    Inheritance

  • 8/6/2019 Ch05 Inheritance

    4/51

    Basics Inheritance is the technique of creating a new

    class by building upon an existing classdefinition.

    In this process, the new class acquires the

    properties and methods of the existing class. The existing class is referred to as parent or

    super or base class, and the new class is

    called a child orsub orderived class.

  • 8/6/2019 Ch05 Inheritance

    5/51

    Types of Inheritance1. Single Inheritance

    B

    X

    2. Hierarchical Inheritance

    B

    X Y Z

  • 8/6/2019 Ch05 Inheritance

    6/51

    3. Multilevel Inheritance

    X

    Y

    Z

    The ObjectClassThe Object class defined in java.lang package

    specifies the topmost (i.e. root) class of the Javaclass hierarchy tree. In the absence of any other

    explicit superclass, every class is implicitly a

    subclass of the Objectclass.

  • 8/6/2019 Ch05 Inheritance

    7/51

  • 8/6/2019 Ch05 Inheritance

    8/51

    class Room extends Rectangle // sub class

    {

    int hgt ;//. other members of Room

    }

    Classes in Java can only inherit one class at a

    time (single inheritance). A subclass can declare new fields / methods

    that are not in the superclass.

  • 8/6/2019 Ch05 Inheritance

    9/51

    // Single inheritance with factorial computationclass Base { // super class

    int ctr ;void factorial( ) {int i, fact = 1 ;for(i = ctr ; i > 0 ; i ) fact = i ;

    System.out.println(Factorial = +fact) ;}

    } // end of Base classclass Derv extends Base { // subclass

    void setCtr(int n) {ctr = n ;

    }

    }

  • 8/6/2019 Ch05 Inheritance

    10/51

    class Test {public static void main(String args[ ]) throwsException{

    Derv od = new Derv( ) ; // derived class objectod.setCtr(5) ;

    od.factorial( ) ; // derv. class accesses membersof base class}

    } Inheritance and Member Accessibility

    The accessibility of base class members inside asub class depends on the fact that whether the

    subclass belongs to same base classs

    package.

  • 8/6/2019 Ch05 Inheritance

    11/51

    Base Class

    Visibility

    Derived Class Visibility

    Within baseclasss package

    Outside baseclasss package

    private Not inherited Not inheritedprotected Yes Yes

    public Yes Yes

    default(nomodifier) Yes No

    Visibility of Class MembersNote Private members are neither accessible

    norinheritable outside the class.

    subclass belongs to some other package.

  • 8/6/2019 Ch05 Inheritance

    12/51

    A subclass inherits all of the public and

    protected members 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

    (default) members of the parent. A subclass does not inherit the private

    members of its parent class. However, inherited

    public orprotected methods of the parent class

    can be used for accessing the private fields bythe subclass.

    Also the subclass does not inherit the

    constructors from its base class.

  • 8/6/2019 Ch05 Inheritance

    13/51

    // Single inheritance and Member Accessibilityclass Circle { // super class

    private double rad ; // private accessdouble getRad( ) { // default accessreturn rad ;

    }

    void setRad(double val) { // default accessrad = val < 0 ? 0.0 : val ;

    }public double calcDiam( ) { // public access

    return (rad 2) ;}public double calcCirc( ) { // public access

    double c = calcDiam( )

    3.14 ;

  • 8/6/2019 Ch05 Inheritance

    14/51

    return c ;}

    public double calcArea( ) { // public accessdouble a = rad rad 3.14 ;return a ;

    }

    }class Sphere extends Circle { // subclass

    public void display( ) {System.out.println(\nSphere Properties) ;

    // System.out.println(rad) ;rad has private accessSystem.out.println(Side: +getRad( )) ;System.out.println(Diameter: +calcDiam( )) ;

    System.out.println(Circumferance: +calcCirc( ));

  • 8/6/2019 Ch05 Inheritance

    15/51

    System.out.println(Area: +calcArea( )) ;} // end of display

    } // end of sub classclass Test{

    public static void main(String args[ ]) throws Exception

    {Sphere ball = new Sphere( ) ; // subclass objectball.setRad(25.55) ; // accesses default memberball.display( ) ; // accesses public member

    }}

  • 8/6/2019 Ch05 Inheritance

    16/51

    Sphere

    Inherited fromCircle

    Structure of Class Sphere

    default

    getRad( )setRad( )

    public

    calcDiam( )calcCirc( )

    calcArea( )

    display( )

  • 8/6/2019 Ch05 Inheritance

    17/51

    It provides the best encapsulation while still

    permitting inheritance. A protected member in Java is a hybrid

    between a defaultand apublicmember. Like default members, protectedmembers are

    accessible inside its own class, and othernonsubclasses in the same package, but notavailable to statements outside the classspackage.

    Like public members, protected members areinherited by derived classes and are accessibleto member functions in the derived class of any

    package.

    Theprotectedvisibility

  • 8/6/2019 Ch05 Inheritance

    18/51

    // Inheritance withprotectedvisibilityclass Rectangle { // superclass

    private int width ;protected int depth ;protected int getWidth( ) {

    return width ;

    }protected void setWidth(int w) { // protected access

    width = w ;}

    }class Box extends Rectangle { // subclass

    private int height ;

    public void setHeight(int h) {

  • 8/6/2019 Ch05 Inheritance

    19/51

    height = h ;}

    int boxArea( ) {int ar, w ;// ar = width depth ; Error: width has private

    access

    // accessing protected inherited membersw = getWidth( ) ; // inherited method accesses

    privatefieldar = w depth ;

    return ar ;}int boxVol( ) {

    int v = boxArea( )

    height ;

  • 8/6/2019 Ch05 Inheritance

    20/51

    return v ;}

    } // end of classclass Test{

    public static void main(String args[ ]) throws Exception

    {Box a = new Box( ) ; // subclass object// protected inherited method accesses private

    field

    a.setWidth(15) ; // invoking protected methoda.depth = 10 ; // accessing inherited protected

    field

    a.setHeight(12) ;

  • 8/6/2019 Ch05 Inheritance

    21/51

    System.out.println(\nArea = +a.boxArea( )) ;System.out.println(\nVolume = +a.boxVol( )) ;

    }}

  • 8/6/2019 Ch05 Inheritance

    22/51

    Box

    Inherited fromRectangle

    Structure of Class Box

    Output:Area =150

    Volume= 1800

    private

    height

    protecteddepth

    getWidth( )setWidth( )

    public

    setHeight( )boxArea( )boxVol( )

  • 8/6/2019 Ch05 Inheritance

    23/51

    Sub Class ConstructorsA subclass constructor is used to initialize the

    instance variables of both the subclass and thesuperclass.

    The subclass constructor invokes the

    constructor of the superclass, either implicitly orby using the keyword super.

    Syntax:

    super( ) ; // Invoking default parent constructor

    or

    super(parameterlist);// Invoking parameterizedparent constructor

  • 8/6/2019 Ch05 Inheritance

    24/51

    If the superclass definition contains a default

    zero argument constructor then,

    the subclass does not require a constructor or the subclass constructor (if present) does not

    need to invoke super( )

    In either of the cases, the JVM will automatically

    invoke the default zero argument constructor in

    the superclass.If the superclass definition contains a

    parameterized constructor then, the subclassmust have a parameterized constructorexplicitly

    invoking a super() with an argument list

    matching the order and type of the desired super

  • 8/6/2019 Ch05 Inheritance

    25/51

    class constructor.Explicit invocation of a superclass constructor

    must be the first line in the subclass constructor.

  • 8/6/2019 Ch05 Inheritance

    26/51

    // Using superto call superclass constructor

    class B { // superclass

    private int a ;private double b ;

    B(int a, double b ) {System.out.println(Base class constructor called) ;

    this.a = a ; this.b = b ;}

    //..

    }class D extends B { // subclass

    private int x ;

    private double y ;

  • 8/6/2019 Ch05 Inheritance

    27/51

    D(int x, double y, int m, double n) {super(m, n) ; // invoking superclass constructor

    System.out.println(\nSub class constructorcalled);this.x = x ; this.y = y ;

    }

    //}class Test {

    public static void main(String args[ ]) throws Exception

    {D od = new D(3, 7.5, 4, 9.25) ; // subclass object//

    }

  • 8/6/2019 Ch05 Inheritance

    28/51

    Output:Base class constructor called

    Sub class constructor called

    Order of Invocation:When a subclass is instantiated, the object will

    begin with an invocation of the constructor in thebase classand initialize downwards through

    constructors in each subclass till it reaches the

    final subclass constructor.

  • 8/6/2019 Ch05 Inheritance

    29/51

    Instance Variable Hiding If a subclass declares a variable / field with the

    same name as one in the superclass, then thesubclass variable hides the inherited superclass

    variable. The hidden variable / field can be accessed

    using the keyword superas:

    super. variablename

  • 8/6/2019 Ch05 Inheritance

    30/51

    // Using superto refer an inherited hidden fieldclass B { // superclass

    int i ;}class D extends B { // subclass

    int i ; // hides field i of base classprivate double y ;D(int a, int b) {

    super.i = a ; // refers to inherited hidden field i this.i = b ;

    }void show( ) {

    System.out.println(Hidden field: +super.i) ;System.out.println(Visible field: +i) ;

    }

  • 8/6/2019 Ch05 Inheritance

    31/51

    } // end of class D

    class Test {

    public static void main(String args[ ]) throwsException

    {

    D od = new D(10, 20) ; // subclass object

    od.show( );}

    }Output:Hidden field: 10Visible field: 20

  • 8/6/2019 Ch05 Inheritance

    32/51

    Method Overriding It is a concept which occurs when an instance

    method in a subclass hides or overrides aninherited method of the superclass due to

    similar declarations. Overridden methods are methods that are

    redefined within an inherited class or subclass.

    They have the same signature, return types and

    access modifiers as the ones in the superclass.

    An overridden superclass method can beinvoked in a subclass using the keyword super

    as:

    super. overriddenMethod( ) ;

  • 8/6/2019 Ch05 Inheritance

    33/51

    // Using superto invoke an overridden methodclass B { // superclass

    private int x ;B(int x) {

    this.x = x ;}void display( ) {

    System.out.println(Super x = +x) ;}

    }class D extends B { // subclass

    int y ;D(int x, int y) {

    super(x) ; // invoking parent constructor

    this.y = y ;

  • 8/6/2019 Ch05 Inheritance

    34/51

    }void display( ) // overriding method redefinition

    { super.display( ) ; // invoking hidden parent methodSystem.out.println(Sub y = +y) ;

    }

    }class Test {

    public static void main(String args[ ]) throwsException

    {D od = new D(10, 20) ;od.display( ) ; // invokes display( ) of D

    }

  • 8/6/2019 Ch05 Inheritance

    35/51

    Output:Super x = 10

    Sub y = 20

    The superkeyword is used whenever a subclass

    needs refer to its immediate superclass. Thereforeit may used to eitheraccess a superclass member

    (method or instance variable) or invoke a parent

    classs constructor.

    Use of keyword super:

  • 8/6/2019 Ch05 Inheritance

    36/51

    Abstract ClassesAn abstract class defines a structure of given

    abstraction without any implementation. In Java, an abstract class is a special type of

    superclass that is specified by using the

    abstractkeyword as:

    abstractclass < classname >

    { . }Abstract classes cannot be instantiated, as they

    are defined solely for the purpose of extension(inheritance) by other classes.

    An abstract class may or may not have abstract

    methods.

  • 8/6/2019 Ch05 Inheritance

    37/51

    Abstract Methods It is an overridden method which is declared with

    the abstract modifier in an abstract superclass,but implemented specifically in a subclass.

    Declaration Syntax:

    abstracttype ([ parameterlist ]) ;

    An abstract method is used when a superclass isunable to create meaningful implementation for a

    method. Abstract methods are sometimes referred to as

    subclasser responsibility since they have noimplementation defined in the superclass.

  • 8/6/2019 Ch05 Inheritance

    38/51

    // Code segment for an abstract class and methodabstract class Figure { // abstract superclass

    //abstract void draw( ) ; // abstract method declaration//

    }class Square extends Figure { // subclass

    //void draw { // abstract method definition ver.1

    System.out.println(Drawing Square) ;

    }//}class Triangle extends Figure { // subclass

    //

  • 8/6/2019 Ch05 Inheritance

    39/51

    void draw { // abstract method definition ver.2System.out.println(Drawing Triangle) ;

    }//

    } // end of class An abstract class is used to create a superclass

    reference variable, that can be used to point toa subclass object. The type of subclass object referred to by the

    superclass reference variable at run time

    dynamically determines the execution of thecorrect version of the abstract method, thus

    implementing Javas approach to subclass

    polymorphism.

  • 8/6/2019 Ch05 Inheritance

    40/51

    // Code fragment for subclass polymorphismclass AbsTest {

    //Figure f ; // abstract superclass variableSquare s = new Square( ) ;Triangle t = new Triangle( ) ;f = t ; // f refers to Triangle objectf.draw( ) ; // invokes draw( ) of Trianglef = s ; // f refers to Square objectf.draw( ) ; // invokes draw( ) of Square

    //}

  • 8/6/2019 Ch05 Inheritance

    41/51

    PolymorphismIt is the capability of an action or method to do

    different things based on the object it is actingupon.

  • 8/6/2019 Ch05 Inheritance

    42/51

    Compile Time Run Time

    Also called early or static

    binding.It is achieved using methodoverloading.

    It is a mechanism by whichthe call to an overloadedmethod is resolved by thecompiler at the compiletime.

    Also called late or

    dynamic binding.It is achieved usingmethod overriding.

    It is a mechanism bywhich the call to anoverridden method( related to a subclassobject) is resolved by theJVM at the run time.

  • 8/6/2019 Ch05 Inheritance

    43/51

    // Dynamic binding using an overridden methodabstract class Shape { // abstract super class

    double ar ;abstract void area( ) ; // abstract method declaration}class Circle extends Shape { // subclass

    double radius ;Circle(double r) {

    radius = r ;}

    public void area( ) {// abstract method def. version 1ar = 3.14 radius radius ;System.out.println(Circle area = +ar) ;

    }}

  • 8/6/2019 Ch05 Inheritance

    44/51

    class Triangle extends Shape { // subclass

    double base, height ;

    Triangle(double b, double h) {base = b ; height = h ;

    }

    public void area( ) {// abstract method def. version 2

    ar = base height / 2 ;System.out.println(Triangle area = +ar) ;

    }

    }class PolyTest {

    public static void main(String args[ ]) throws

    Exception

    {

  • 8/6/2019 Ch05 Inheritance

    45/51

    Shape s ;// abstract superclass reference variable

    s = new Circle(2.0) ; // s refers to Circle object

    s.area( ) ; // invokes area( ) of Circles = new Triangle(2.0, 5.0) ; // s refers to Triangle

    obj.

    s.area( ) ; // invokes area( ) of Triangle

    } // end of main} // end of main class

    Output:

    Circle area = 12.56Triangle area = 5.0

  • 8/6/2019 Ch05 Inheritance

    46/51

    A class Student defines the personal data of a student

    while another class Marks defines the marks obtained

    by the student. Their details are:Class name : Student

    Data members:

    name : stores name of student

    age : integer variableMember functions:

    void inpdetails1( ) : to accept values for data

    members

    void show1( ) : to display personal dataof student

  • 8/6/2019 Ch05 Inheritance

    47/51

    Class name : Marks

    Data members:

    regnum, marks : integer type variablessubject : stores name of subject

    Member functions:

    void inpdetails2( ) : to accept values for data

    membersvoid show2( ) : to display exam details

    Specify the class Student giving details of the

    functions. Using the concept of inheritance, specifythe class Marks, giving details of the functions. The

    main function need not be written.

  • 8/6/2019 Ch05 Inheritance

    48/51

    A class Account has the following details:

    Class name : Account

    Protected data members :

    acctNumber : a positive integer

    principle : a double precision real

    number

    Member functions:Account(int a, double p) : parameterized construc

    tor

    void display( ) : to display the data

    Extend class Account to derive two classes: Simple and

    Compound whose details are:

  • 8/6/2019 Ch05 Inheritance

    49/51

    Class name : Simple

    Data members :

    double rate : to store rate

    int time : to store time in years

    Member functions:

    Simple(.) : parameterized construc

    tor to initialize various att-ributes

    void display( ) : to display the data

    double interest( ) : calculates and returns

    the interest using the formula:

    SI = P X R X T/100 where,

    SI = simple interest, T = time, R = rate, P = principle

  • 8/6/2019 Ch05 Inheritance

    50/51

    Class name : Compound

    Data members :

    double rate : to store rate

    int time : to store time in years

    Member functions:

    Compound(.) : parameterized construc

    tor to initialize various attri-butes

    void display( ) : to display the data

    double interest( ) : calculates and returns

    the interest using the formula:

    CI = P[1+R/100]T where,

    CI = compound interest, T = time, R = rate, P = principle

  • 8/6/2019 Ch05 Inheritance

    51/51

    Specify the classes Account, Simple and Compound

    giving details of their constructors and member

    functions. The output should be displayed as :

    Account Number = ..

    Principle = ..

    Rate = ..

    Time = ..Interest = ..

    You need not write the main function.