Inheritence Java

Embed Size (px)

Citation preview

  • 8/2/2019 Inheritence Java

    1/62

    Inheritance

  • 8/2/2019 Inheritence Java

    2/62

    Single InheritanceThe class that is used as a basis

    for defining a new class is called

    aparentclass (or super class orbase class). The new class based

    on the parent class is called a

    childclass (or subclass or derived

    class.)

    In, children inherit characteristics

    fromjust one parent. This is

    called single inheritance. Some

    languages allow a child to inherit

    from more than one parent. This

    is called multiple inheritance.

    Java does not allow multiple

    inheritance

  • 8/2/2019 Inheritence Java

    3/62

    Syntax

    A subclass inherits from a superclass using the

    extends keyword

    Inheritance is applicable to top-level classes,

    nested top-level classes, member classes, localclasses and anonymous classes

    classsubClassNameextendssuperClassName{

    variable and method declarations}

  • 8/2/2019 Inheritence Java

    4/62

    Example

    public class Employee {

    private String name;

    private int id;

    public String getName() {

    return name;}

    public int getId() {

    return id;

    }

    }

    public class SalariedEmployee extends Employee {

    private int rate;

    public int getRate() {

    return rate;

    }

    }

    public class HourlyEmployee extends Employee {

    private int rate;

    private int hours;

    public int getRate() {

    return rate;

    }

    public int getHours() {

    return hours;

    }

    }

  • 8/2/2019 Inheritence Java

    5/62

    Example

    public class Payroll {

    public static void main( String args[] ) {

    SalariedEmployee lisa = new SalariedEmployee();

    HourlyEmployee james = new HourlyEmployee();

    System.out.println( lisa.getName() );

    System.out.println( lisa.getId() );

    System.out.println( lisa.getRate() );

    System.out.println( james.getName() );

    System.out.println( james.getId() );

    System.out.println( james.getRate() );

    System.out.println( james.getHours() );

    }

    }

  • 8/2/2019 Inheritence Java

    6/62

    Example

    public class Payroll {

    public static void printEmployeeInfo( Employee e ) {

    System.out.println( e.getName() );

    System.out.println( e.getId() );

    }

    public static void main( String args[] ) {SalariedEmployee lisa = new SalariedEmployee();

    HourlyEmployee james = new HourlyEmployee();

    printEmployeeInfo ( lisa );

    System.out.println( lisa.getRate() );

    printEmployeeInfo ( james );

    System.out.println( james.getRate() );

    System.out.println( james.getHours() );}

    }

  • 8/2/2019 Inheritence Java

    7/62

    Why Wont This Work?

    public class Payroll {

    public static void printEmployeeInfo( Employee e ) {

    System.out.println( e.getName() );

    System.out.println( e.getId() );

    System.out.println( e.getRate() );

    }

    public static void main( String args[] ) {

    SalariedEmployee lisa = new SalariedEmployee();

    HourlyEmployee james = new HourlyEmployee();

    printEmployeeInfo( lisa );

    System.out.println( lisa.getRate() );

    printEmployeeInfo( james );

    System.out.println( james.getRate() );System.out.println( james.getHours() );

    }

    }

  • 8/2/2019 Inheritence Java

    8/62

    Inheritance

    A class can inherit from any class that is not final.

    Objects of the subclass contain all the instance

    variables and methods declared by the superclass.

    The accessibility rules are still enforced a subclass cannot access the private parts of the

    superclass.

    Subclassing can be repeated as many times as

    desired.

    A class can have only one superclass, but may have

    many subclasses.

  • 8/2/2019 Inheritence Java

    9/62

    Why Wont This Work?

    public class SalariedEmployee extends Employee {

    private int rate;

    public SalariedEmployee( String n, int i, int r ) {

    name = n;

    id = i;rate = r;

    }

    public int getRate() {

    return rate;

    }

    }

  • 8/2/2019 Inheritence Java

    10/62

    Controlling Access to Class Members

    Attribute Permitted accessNo access attribute From any class in the same package

    public From any class anywhere. Enabled a class to

    be accessed outside of its package. It also

    enables a variable, method, or constructor to beaccessed anywhere its class may be accessed

    Private No access from outside the class at all.

    Prevents a variable, method, or constructor

    from being accessed outside of he class inwhich it is declared

    protected Intermediate level of protection. Enables a

    variable, method or constructor to be accessed

    by class or interfaces of the same package or

    by sub-class of the class in which it is declared

  • 8/2/2019 Inheritence Java

    11/62

    The access allowed between classes within the same

    package

    Class 2 Class 1

    int a;

    public int b;ptotected int c;

    private int e;

    Sub-Class 1

    Package 1

    Within a package, only the private members of the class Class 1can not be directly accessed by a method in another class in the same

    package

    No No

  • 8/2/2019 Inheritence Java

    12/62

    The access allowed between classes within different

    packages

    Class 2 Class 1

    int a;

    public int b;ptotected int c;

    private int e;

    Sub-Class 1

    Package 3 Package 1 Package 2

    The only members of Class 1 that can be accessed from an ordinary class,

    Class2 , in another package are those specified as public. Keep in mind thatthe class, Class 1, must also have been defined with the attribute public.

  • 8/2/2019 Inheritence Java

    13/62

    Class designers use private data and public methods toenforce the notion of information hiding and the principle of

    least privilege. If the client of a class needs access to data in

    the class, provide that access through public methods ofthe class.

  • 8/2/2019 Inheritence Java

    14/62

    Access to Inheriting Data Members

    Sub Class

    public int a;

    protected int c;

    Class

    int a;

    public int b;

    ptotected int c;

    private int e;

    Sub-Class 1

    int a ;

    public int b;

    protected int c;

    Package 2 Package 1

    No

    No

    No

    A subclass that you define in the same package as its base inherits everything

    except for private data member of the base public class. Members defined as

    private in the base class are never inherited under anycircumstances.

  • 8/2/2019 Inheritence Java

    15/62

    Constructors and Inheritance

    The guarantee of proper initialization must bemaintained in the presence of inheritance.

    Unless specified, java will call the default constructors

    for each class in the inheritance hierarchy

    Java provides syntax for explicitly controlling

    which constructors are called.

    The keyword super can be used to explicitly call

    a superclass constructor super (argumentList) ;

    supermust be the first statement in a constructor

  • 8/2/2019 Inheritence Java

    16/62

    Example

    public class Employee {

    private String name;

    private int id;

    public Employee( String n, int i ) {

    name = n;

    id = i;}

    public String getName() {

    return name;

    }

    public int getId() {

    return id;

    }}

    public class SalariedEmployee extends Employee {

    private int rate;

    public SalariedEmployee( String n,

    int i,

    int r ) {super( n, i );

    rate = r;

    }

    public int getRate() {

    return rate;

    }

    }

  • 8/2/2019 Inheritence Java

    17/62

    Why Wont This Compile?

    public class Employee {

    private String name;

    private int id;

    public Employee( String n, int i ) {

    name = n;

    id = i;}

    public String getName() {

    return name;

    }

    public int getId() {

    return id;

    }}

    public class SalariedEmployee extends Employee {

    private int rate;

    public SalariedEmployee( String n,

    int i,

    int r ) {rate = r;

    }

    public int getRate() {

    return rate;

    }

    }

  • 8/2/2019 Inheritence Java

    18/62

    Protected

    Java provides a third access type calledprotected

    Instance variables defined as protected can be

    accessed by any subclass

    by classes defined within the same package

    Some feel that protected breaks encapsulation

    Make everything private

  • 8/2/2019 Inheritence Java

    19/62

    Example

    public class Employee {

    protected String name;

    protected int id;

    public String getName() {

    return name;

    }

    public int getId() {

    return id;

    }

    }

    public class SalariedEmployee extends Employee {

    private int rate;

    public SalariedEmployee( String n,

    int i,

    int r ) {name = n;

    id = i;

    rate = r;

    }

    public int getRate() {

    return rate;

    }

    }

  • 8/2/2019 Inheritence Java

    20/62

    Scope Rules

    Inheritance increases the number of scopes that

    need to be searched (both static and instance

    declarations are searched)

    check the local scope check the class scope

    check each superclass scope in turn up to the top of the

    inheritance chain

    If variables with the same identifier are declared inseveral scopes, the first one found is used.

  • 8/2/2019 Inheritence Java

    21/62

    Method Overloading

    Methods can beoverloaded, meaning that: Two or more methods in the same class:

    can have the same name

    provided they have different parameter lists, and

    the return type is the same.

    In a class with an overloaded method, all versionsof the method are available.

    (Note that method overloading does not reallyhave anything to do with inheritance, but we willnext discuss overriding, which is easilyconfused with overloading.)

  • 8/2/2019 Inheritence Java

    22/62

    Method Overriding

    A subclass canoverridean inherited method byproviding a new method declaration that

    has the same name,

    has the same parameter list (in type and number) and

    has the same return type as the one inherited.

    Only the overridden method is directly accessible

    The original method is still there, but you have to usesuper to access it

    Method overriding relies on dynamic binding, sothe type of the object determines which methodgets called.

  • 8/2/2019 Inheritence Java

    23/62

    Class Object

    Every class in Java inherits from the class Object

    Class Object declares the following methods

    that can be overridden:

    public boolean equals( Object obj );public String toString();

    public final native int hashCode();

    protective native Object clone();

    protected void finalize();

    public final Class getClass()

  • 8/2/2019 Inheritence Java

    24/62

    Example

    public class Employee {

    private String name;

    private int id;

    public Employee( String n,

    int i ) {

    name = n;

    id = i;

    }

    public String getName() {

    return name;

    }

    public int getId() {

    return id;

    }

    public String toString() {

    return name +

    ", " +

    id;

    }}

    public class SalariedEmployee extends Employee {

    private int rate;

    public SalariedEmployee( String n,

    int i,

    int r ) {

    super( n, i );

    rate = r;

    }

    public int getRate() {

    return rate;

    }

    public String toString() {

    return getName() +

    ", " +getId() +

    ", " +

    rate;

    }

    }

  • 8/2/2019 Inheritence Java

    25/62

    public class Employee {

    private String name;

    private int id;

    public Employee( String n,

    int i ) {

    name = n;

    id = i;

    }

    public String getName() {

    return name;

    }

    public int getId() {

    return id;

    }

    public String toString() {

    return name +

    ", " +

    id;

    }}

    public class SalariedEmployee extends Employee {

    private int rate;

    public SalariedEmployee( String n,

    int i,

    int r ) {

    super( n, i );

    rate = r;

    }

    public int getRate() {

    return rate;

    }

    public String toString() {

    return super.toString() +

    ", " +rate;

    }

    }

  • 8/2/2019 Inheritence Java

    26/62

    Did You Ever Wonder

    Did you ever wonder how println() or

    print() work?

    println() is an overloaded method

    void println(boolean x) void println(char x)

    void println(int x)

    void println(double x)

  • 8/2/2019 Inheritence Java

    27/62

    27

    Final and Abstract Classes& Interfaces

  • 8/2/2019 Inheritence Java

    28/62

    28

    Restricting Inheritance

    Parent

    Child

    Inheritedcapability

    Fi l M b A f P ti

  • 8/2/2019 Inheritence Java

    29/62

    29

    Final Members: A way for PreventingOverriding of Members in Subclasses

    All methods and variables can be overridden bydefault in subclasses.

    This can be prevented by declaring them as

    final using the keyword final as a modifier.For example: final int marks = 100;

    final void display();

    This ensures that functionality defined in thismethod cannot be altered any. Similarly, thevalue of a final variable cannot be altered.

    Fi l Cl A f P ti

  • 8/2/2019 Inheritence Java

    30/62

    30

    Final Classes: A way for PreventingClasses being extended

    We can prevent an inheritance of classes by otherclasses by declaring them as final classes.

    This is achieved in Java by using the keyword final asfollows:

    final class Marks{ // members

    }

    final class Student extends Person

    { // members

    }

    Any attempt to inherit these classes will cause an error.

  • 8/2/2019 Inheritence Java

    31/62

    computePay()

    For the Employee class we would like to add acomputePay() method

    Where do we put it? Cant put it in the Employeeclass since we dont know how

    to compute the pay for a generic employee

    We really dont want to put it in the subclasses because wewont be able to say, for a generic Employee:

    Employee x; x.computePay()

    What we really want is:1. a placeholder in the Employee class, and

    2. the method definition in each sublcass

  • 8/2/2019 Inheritence Java

    32/62

    Abstract Methods

    A method can be declaredabstract so that it must

    be overridden by subclasses.

    An abstract method does not have a method body;

    the method declaration ends with a semi-colon,not a compound statement.

    A class declaring one or more abstract methods

    must be declared as anabstract class

    Private and static methods cannot be abstract

  • 8/2/2019 Inheritence Java

    33/62

    33

    Abstract Classes

    When we define a class to be final, it cannotbe extended. In certain situation, we want toproperties of classes to be always extended andused. Such classes are called Abstract Classes.

    An Abstractclass is a conceptual class. An Abstractclass cannot be instantiated

    objects cannot be created.

    Abstract classes provides a common root for agroup of classes, nicely tied together in apackage:

  • 8/2/2019 Inheritence Java

    34/62

    computePay()public abstract class Employee {

    private String name;

    private int id;

    public Employee( String n,

    int i ) {

    name = n;

    id = i;

    }

    public String getName() {

    return name;}

    public int getId() {

    return id;

    }

    public abstract int computePay();

    public String toString() {

    return name +

    ", " +

    id;

    }

  • 8/2/2019 Inheritence Java

    35/62

    computePay()public class SalariedEmployee extends

    Employee {

    private int rate;

    public SalariedEmployee( String n,

    int i,

    int r ) {

    super( n, i );

    rate = r;

    }

    public int getRate() {

    return rate;

    }

    public int computePay() {

    return rate;

    }

    public String toString() {

    return super.toString() +

    ", " +

    rate;

    }

    }

  • 8/2/2019 Inheritence Java

    36/62

    36

    Abstract Class Syntax

    abstract class ClassName{

    ...abstract Type MethodName1();Type Method2(){

    // method body}

    } When a class contains one or more abstract methods, it should be

    declared as abstract class. The abstract methods of an abstract class must be defined in its

    subclass. We cannot declare abstract constructors or abstract static

    methods.

  • 8/2/2019 Inheritence Java

    37/62

    37

    Abstract Class -Example

    Shape is a abstract class.

    Shape

    Circle Rectangle

  • 8/2/2019 Inheritence Java

    38/62

    38

    The Shape Abstract Class

    Is the following statement valid? Shape s = new Shape();

    No. It is illegal because the Shape class is an abstractclass, which cannot be instantiated to create its objects.

    public abstract class Shape {public abstract double area();

    public void move() { // non-abstract method

    // implementation

    }}

  • 8/2/2019 Inheritence Java

    39/62

    39

    Abstract Classes

    public Circle extends Shape {

    protected double r;

    protected static final double PI =3.1415926535;

    public Circle() { r = 1.0; )public double area() { return PI * r * r; }

    }

    public Rectangle extends Shape {

    protected double w, h;

    public Rectangle() { w = 0.0; h=0.0; }

    public double area() { return w * h; }

    }

  • 8/2/2019 Inheritence Java

    40/62

    40

    Abstract Classes Properties

    A class with one or more abstract methods isautomatically abstract and it cannot beinstantiated.

    A class declared abstract, even with no abstract

    methods can not be instantiated. A subclass of an abstract class can be

    instantiated if it overrides all abstract methodsby implementation them.

    A subclass that does not implement all of thesuperclass abstract methods is itself abstract;and it cannot be instantiated.

  • 8/2/2019 Inheritence Java

    41/62

    41

    Summary

    If you do not want (properties of) your class to beextended or inherited by other classes, define it as afinal class. Java supports this is through the keyword final. This is applied to classes.

    You can also apply the final to only methods if you donot want anyone to override them.

    If you want your class (properties/methods) to beextended by all those who want to use, then define itas an abstract class or define one or more of itsmethods as abstract methods. Java supports this is through the keyword abstract. This is applied to methods only. Subclasses should implement abstract methods; otherwise,

    they cannot be instantiated.

  • 8/2/2019 Inheritence Java

    42/62

    42

    Interfaces

    Design Abstraction and a way for

    realizing Multiple Inheritance

  • 8/2/2019 Inheritence Java

    43/62

    43

    Interfaces

    Interface is a conceptual entity similar to aAbstract class.

    Can contain only constants (final variables) and

    abstract method (no implementation) -Different from Abstract classes.

    Use when a number of classes share acommon interface.

    Each class should implement the interface.

  • 8/2/2019 Inheritence Java

    44/62

    44

    Syntax

    An interface is declared as shown below:

    The optional interfaceModifierallows aninterface to be declared public.

    Any variables declared in an interface are: implicitly constants, and also

    static

    interfaceModifierinterfaceidentifier{

    interfaceVariableDeclarations;

    interfaceMethodDeclarations;

    }

    Interfaces: An informal way of

  • 8/2/2019 Inheritence Java

    45/62

    45

    Interfaces: An informal way ofrealising multiple inheritance

    An interface is basically a kind of classit containsmethods and variables, but they have to be onlyabstract classes and final fields/variables.

    Therefore, it is the responsibility of the class thatimplements an interface to supply the code formethods.

    A class can implement any number of interfaces, butcannot extend more than one class at a time.

    Therefore, interfaces are considered as an informal way

    of realising multiple inheritance in Java.

  • 8/2/2019 Inheritence Java

    46/62

    46

    Implements

    The implements keyword allows a class toimplement (conform to) one or more interfaces.

    A class can implement any number of interfaces

    (and also extend a class at the same time). Any variables defined in the interface become

    static constants of the class.

    A method declared in a public interface must bepublic in an implementing class.

  • 8/2/2019 Inheritence Java

    47/62

    47

    Interface - Example

    speak()

    Politician Priest

    Speaker

    speak() speak()

    Lecturer

    speak()

  • 8/2/2019 Inheritence Java

    48/62

    48

    Interfaces Definition

    Syntax (appears like abstract class):

    Example:

    interface InterfaceName {

    // Constant/Final Variable Declaration

    // Methods Declaration only method body}

    interface Speaker {

    public void speak( );

    }

  • 8/2/2019 Inheritence Java

    49/62

    49

    Implementing Interfaces

    Interfaces are used like super-classeswhose properties are inherited by classes.This is achieved by creating a class that

    implements the given interface asfollows:

    class ClassName implements InterfaceName [, InterfaceName2, ]

    {// Body of Class

    }

  • 8/2/2019 Inheritence Java

    50/62

    50

    Implementing Interfaces Exampleclass Politician implements Speaker {

    public void speak(){System.out.println(Talk politics);

    }

    }

    class Priest implements Speaker {public void speak(){

    System.out.println(Religious Talks);}

    }

    class Lecturer implements Speaker {

    public void speak(){

    System.out.println(Talks Object Oriented Design and Programming!);}

    }

  • 8/2/2019 Inheritence Java

    51/62

    51

    Extending Interfaces

    Like classes, interfaces can also be extended.The new sub-interface will inherit all themembers of the superinterface in the manner

    similar to classes. This is achieved by using thekeyword extends as follows:

    interface InterfaceName2 extendsInterfaceName1

    { // Body of InterfaceName2

    }

    Inheritance and Interface

  • 8/2/2019 Inheritence Java

    52/62

    52

    Inheritance and InterfaceImplementation

    A general form of interface implementation:

    This shows a class can extended another class whileimplementing one or more interfaces. It appears like a

    multiple inheritance (if we consider interfaces as specialkind of classes with certain restrictions or specialfeatures).

    class ClassName extends SuperClass implements InterfaceName [,

    InterfaceName2, ]

    {// Body of Class

    }

  • 8/2/2019 Inheritence Java

    53/62

    Example

    public interface Calculator {public int add ( int x, int y );

    public int sub ( int x, int y );

    public int mult( int x, int y );

    public int div ( int x, int y );

    };

    public class StandardCalculator implements Calculator {

    public int add ( int x, int y ) { return x + y; }

    public int sub ( int x, int y ) { return x - y; }

    public int mult( int x, int y ) { return x * y; }

    public int div ( int x, int y ) { return x / y; }

    }

  • 8/2/2019 Inheritence Java

    54/62

    Example

    public interface StatCalculator {public double avg( int[] x );

    public double sum( int x[] );

    public double std( int[] x );

    }

    public class CalculatorWithStats implements Calculator, StatCalculator {

    public int add ( int x, int y ){ return x + y; };

    public int sub ( int x, int y ){ return x - y; };

    public int mult( int x, int y ){ return x * y; };

    public int div ( int x, int y ){ return x / y; };

    public double avg( int[] x ) { return sum( x ) / x.length; }

    public double sum( int[] x ) {

    double s = 0;

    for ( int i = 0; i < x.length; i++ ) { s = s + x[ i ]; }

    return s;

    }

    public double std( int[] x ) {

    double retVal = 0;

    if ( x.length > 1 ) {

    double sumDiff = 0;

    double average = avg( x );

    for ( int i = 0; i < x.length; i++ ) {

    double diff = x[ i ] - average;

    sumDiff = sumDiff + diff * diff;

    }

    retVal = Math.sqrt( sumDiff / ( x.length - 1 ) );

    }

    return retVal;

    }

    }

    public interface Calculator {

    public int add ( int x, int y );

    public int sub ( int x, int y );

    public int mult( int x, int y );

    public int div ( int x, int y );

    }

  • 8/2/2019 Inheritence Java

    55/62

    Examplepublic class CalculatorWithStats2 extends StandardCalculator implements StatCalculator {

    public double avg( int[] x ) { return sum( x ) / x.length; }

    public double sum( int[] x ) {

    double s = 0;

    for ( int i = 0; i < x.length; i++ ) { s = s + x[ i ]; }

    return s;

    }

    public double std( int[] x ) {

    double retVal = 0;

    if ( x.length > 1 ) {

    double sumDiff = 0;

    double average = avg( x );

    for ( int i = 0; i < x.length; i++ ) {

    double diff = x[ i ] - average;

    sumDiff = sumDiff + diff * diff;

    }

    retVal = Math.sqrt( sumDiff / ( x.length - 1 ) );

    }

    return retVal;

    }

    }

  • 8/2/2019 Inheritence Java

    56/62

    Testing the Calculator Class

    public class TestCalculator {

    public static void main( String args[] ) {

    int x = 4;

    int y = 6;

    int z = 7;

    int[] numbers = {2,4,6};

    CalculatorWithStats2 calc = new CalculatorWithStats2();

    System.out.println( x + " + " + y + " = " + calc.add ( x, y ) );

    System.out.println( x + " * " + z + " = " + calc.mult( x, z ) );

    System.out.println( "avg of "

    + numbers[0] + ", " + numbers[1] + ", "

    + numbers[2] + " = + calc.avg( numbers ) );System.out.println( "std dev of "

    + numbers[0] + ", " + numbers[1] + ", "

    + numbers[2] + " = + calc.std( numbers ) );

    }}

  • 8/2/2019 Inheritence Java

    57/62

    Inheritance Among Interfaces

    public interface StatCalculator extends Calculator

    {

    public double avg( int[] x );

    public double sum( int x[] );

    public double std( int[] x );}

  • 8/2/2019 Inheritence Java

    58/62

    Static

    Classes are mostly used to create objects, But a class has an existence. A class

    and its objects are different types of things.

    In the Java language, characteristics of a class definition (but not of its objects)

    are called static. There is only one class definition for a given class, so when a

    program is running, if something is static then there is only one of it.

    You can think of the word static as meaning "no matter how many objects are

    made, there will be only one of these."

  • 8/2/2019 Inheritence Java

    59/62

    Static Methods

    The methods that a class definition has are called staticmethods. (Sometimes they are called class methods, but

    this is confusing.) A static method is a characteristic of a

    class, not of the objects it has created.

    Important:A program can execute a static methodwithout first creating an object!All other methods (not

    static) must be part of an object, so an object must

    exist before they can be executed.

    Th t ti M difi

  • 8/2/2019 Inheritence Java

    60/62

    The static Modifier

    Static methods can be invoked through the class name ratherthan through a particular object

    For example, the methods of the Math class are static:

    Math.sqrt (25)

    To write a static method, we apply the static modifier to themethod definition

    The static modifier can be applied to variables as well

    It associates a variable or method with the class rather thanwith an object

  • 8/2/2019 Inheritence Java

    61/62

    Static Variables Static variables are also called class variables

    Normally, each object has its own data space, but if a variable

    is declared as static, only one copy of the variable exists

    private static float price;

    All objects created from the class share static variables

    Changing the value of a static variable in one object changes it

    for all others

  • 8/2/2019 Inheritence Java

    62/62

    Static Methods

    The order of the modifiers can be interchanged, but byconvention visibility modifiers come first

    Recall that the main method is static; it is invoked by thesystem without creating an object

    Static methods cannot reference instance variables,because instance variables don't exist until an object exists

    However, a static method can reference static variables or

    local variables