63
UNIT-2-CHAPTER-3 INHERITANCE

Chap3 inheritance

Embed Size (px)

Citation preview

Page 1: Chap3 inheritance

UNIT-2-CHAPTER-3

INHERITANCE

Page 2: Chap3 inheritance

Inheritance basics

Java supports inheritance by allowing oneclass to incorporate another class into itsdeclaration

Done using a keyword “extend”

Subclass adds to (extends ) the superclass

A class that is inherited is called a superclass

The class that does the inheriting is calledsubclass

Hence subclass is a specialized version ofsuperclass

It inherits all of the variables and methodsdefined by the super class and adds its ownunique variable

Page 3: Chap3 inheritance
Page 4: Chap3 inheritance
Page 5: Chap3 inheritance
Page 6: Chap3 inheritance

the triangle class includes all TwoDObject andadds the field style and a method area() andmethod showStyle().

The triangle ‘s style is stored in style.

this can be any string that describes thetriangle such as “filled” “outlined”,“transparent”, “isosceles” or “rounded”.

The area() method computes and returns thearea of the triangle, showStyle() displays thetriangle style.

Page 7: Chap3 inheritance

The general form of a class declaration that inherits asuperclass is shown here:

class subclass_name extends superclass_name{

//body of the class

}

Can mention one superclass for any subclass that youcreate.

Java does not support the inheritance of multiplesuper classes into a single subclass

Allows to create a hierarchy of inheritance in which asubclass becomes a super class of another subclass.

No class is superclass of itself.

Page 8: Chap3 inheritance

Advantage of inheritance

Once you have created a superclass that

defines the attributes common set of objects, it

can be used to create any number of more

specific subclass

Page 9: Chap3 inheritance

Member access and inheritance

A subclass includes all of the members of itssuperclass it cannot access those members of thesuperclass that have been declared private

class TwoDshape{

private double width;

private double height;

…..

double area(){

return width*height /2;

}

}

Page 10: Chap3 inheritance

Program will not compile because thereference to width and height inside the area()method causes an access violation.

Since width and height members are private innature, they are accessible only by othermembers of their own class.

Private members are not accessible outsidethe class, even subclasses.

Java uses accessor methods to provideaccess to the private members of the class.

Page 11: Chap3 inheritance
Page 12: Chap3 inheritance
Page 13: Chap3 inheritance

Constructors and inheritance

The constructor for the superclass constructs

the superclass portion of the object,

constructor for the subclass constructs the

subclass part.

The superclass has no knowledge of access to

any element in a subclass., hence their

construction must be separate.

The superclass portion of the object is

constructed automatically using a default

constructor.

Page 14: Chap3 inheritance
Page 15: Chap3 inheritance
Page 16: Chap3 inheritance
Page 17: Chap3 inheritance
Page 18: Chap3 inheritance

Here triangle’s constructor initializes the

members of the TwoD class that it inherits

along with its own style field.

When both the superclass and the subclass

defines as constructor, the process is more

complicated because both superclass and

subclass constructor must be executed.

Page 19: Chap3 inheritance

Using super to call Superclass

constructors

A subclass can call a constructor defined by itssuperclass by the use of the following form ofsuper:

Super(parameter_list);

Here parameter_list specifies any parameterneeded by the constructor in the superclass

super() must be the first statement executedinside a subclass constructor

Eg: defines a constructor that initializes widthand height varaible in the TwoDShapeprogram.

Page 20: Chap3 inheritance
Page 21: Chap3 inheritance
Page 22: Chap3 inheritance
Page 23: Chap3 inheritance

Triangle() calls super() with parameters w and h.

This causes the TwoDshape() constructor to be

called, which initialize width and height using

these values.

Triangle no longer initializes these values itself.

TwoDshape can add functionality about which

existing subclasses have no knowledge, thus

preventing existing code from breaking.

Any form of constructor defined by the superclass

can be called by super()

The constructor executed will be one that matches

the arguments.

Page 24: Chap3 inheritance
Page 25: Chap3 inheritance
Page 26: Chap3 inheritance
Page 27: Chap3 inheritance
Page 28: Chap3 inheritance

When a subclass calls super(), it is calling the

constructor of its immediate superclass.

Super() always refers to the superclass

immediately above the calling class.

It is true even in a multilevel hierarchy

super() must always be the first statement

executed inside a constructor.

Page 29: Chap3 inheritance

Using super to access superclass

members

Using super we can refer to the members of

the superclass.

General form is as follows:

super.member

Here the member can be either a method or

an instance variable.

Used when the members of the subclass hide

members by the same in the superclass.

Page 30: Chap3 inheritance
Page 31: Chap3 inheritance
Page 32: Chap3 inheritance

Creating a multilevel hierarchy

Assume that there are three classes A,B and C

where C is a subclass of B, which in turn is

subclass of A.

Here class C will inherit all of the traits found in

subclasses.

Page 33: Chap3 inheritance
Page 34: Chap3 inheritance
Page 35: Chap3 inheritance
Page 36: Chap3 inheritance

When are constructors called?

Constructors are called in the order of

derivation from superclass to subclass.

Super() must be the first statement executed in

subclass constructor.

If super() is not used then the default

constructor will be executed.

Page 37: Chap3 inheritance
Page 38: Chap3 inheritance
Page 39: Chap3 inheritance

Superclass references and

subclass objects

Java is strongly typed language

type compatibility is strictly enforced

A reference variable for one class type cannotnormally refer to an object of another class type.

class X{

int a;

x(int i)

{

a= i ;

}

}

Page 40: Chap3 inheritance

class Y{

int a;

Y(int i){

a=i;

}

}

class incompatibletypes{

X objx1=new X(10);

X objx2;

Y y=new Y(15);

objx2=x; // OK, both of same type

objx2=y; //error , not of same type

}

Page 41: Chap3 inheritance

Class x and y are physically same, it is not

possible to assign an X reference to Y object

they have different types.

An object can only refer a object of its type.

A reference variable of superclass can be

assigned a reference to an object of any

subclass derived from that superclass.

A superclass object can refer to a subclass

object.

Page 42: Chap3 inheritance

class X{

int a;

X (int i)

{

a=i;

}

}

class Y extends X{

int b;

Y(int i, int j){

super(j);

b= i;

}

class SupSub{

public static void main(Stringargs[]){

X x1=new X(10);

X x2;

Y y=new Y(5,6);

x2=x1;

System.out.println(“x2.a:”+x2.a);

x2=y;

System.out.println(“x2.a:”+x2.a);

X2.a=19; //OK

X2.b=27; //error, x does not have aand b member

}

}

Page 43: Chap3 inheritance

Method overriding

When a method in a subclass has the same

return type and signature as a method in its

superclass, then the method in the subclass is

said to be override the method in superclass.

When an overridden method is called from

within a subclass , it will always refer to the

version of that method defined by the

subclass.

The version defined by the superclass will be

hidden.

Page 44: Chap3 inheritance
Page 45: Chap3 inheritance

If the superclass version of an overridden

method has to be accessed then, you can do

so by using super().

Method overriding occurs only when the

signatures of the two methods are identical.

If they are not then, the two methods are

simply overloaded.

Page 46: Chap3 inheritance
Page 47: Chap3 inheritance

Overridden methods support

polyorphsim

Dynamic method dispatch

Mechanism by which call to an overriddenmethod is resolved at run time rather thancompile time

Dynamic method dispatch is importantbecause this how java implements run-timepolymorphism.

Is superclass reference variable can refer to asubclass objects.

Java determines which version of that methodto execute based upon the type of object beingreferred to at a time the call occurs.

Page 48: Chap3 inheritance

When different types of objects are referred to,

different versions of overridden method will be

called.

It is the type of the objects being referred to that

determines which version of an overridden

method will be executed.

If a superclass contains a method that is

overridden by a subclass, then when different

types of objects are referred to through a

superclass reference variable , different versions

of the method are executed.

Page 49: Chap3 inheritance
Page 50: Chap3 inheritance
Page 51: Chap3 inheritance
Page 52: Chap3 inheritance

Why overridden methods?

It allows to support polymorphism in JAVA

Polymorphism allows a general class to specify

methods that will be common to all of its

derivatives, while allowing subclasses to define

the specific implementation of some or all of those

methods.

It helps to implement “one interface, multiple

methods”

By combining inheritance with the overridden

methods, a superclass can define the general

form of methods that will be used by all of its

subclasses.

Page 53: Chap3 inheritance

Using Abstract Classes

A class that determines the nature of methods

that subclasses must implement but does not

itself provide any implementation of one or

more of these methods, such a class is called

abstract class

Defined by specifying the abstract type

modifier.

It contains no body and is there not

implemented by the superclass

The subclass must override it

abstract type name(parameter_list);

Page 54: Chap3 inheritance

No body is present, the abstract modifier canbe used only on normal methods.

Cannot be applied to static methods or toconstructors.

A class that contains one or more abstractmethod should be declared as abstract classwith the abstract modifier.

Since abstract class does not define acomplete implementation, there can be noobjects of an abstract class.

Page 55: Chap3 inheritance

Attempting to create an object of an abstract

class, will lead to a compile time error.

When a subclass inherits an abstract class, it

should implement all of the abstract method in

superclass

If it does not, then the subclass must be

specified as abstract.

Hence abstract is inherited until complete

implementation of the methods are achieved.

Page 56: Chap3 inheritance
Page 57: Chap3 inheritance

Using final

To prevent a method from overridden, specify

that method with a keyword “final” at the start

of its declaration

Methods declared as final cannot be

overridden

example

Page 58: Chap3 inheritance
Page 59: Chap3 inheritance

Final prevents inheritance

By having a class declared as final, inheritance can beprevented

By declaring a class as final, implicitly it declares althe methods as final too.

Using abstract and final together is illegal because,abstract depends on the subclass for itsimplementations and final avoids inheritance.

final class A{

//….

}

class B extends A{ //error cant have subclass of A

//….

}

Page 60: Chap3 inheritance

Using final with data members

final can be applied on data members of the

class.

If we have members of class as final, the value

cannot be changed throughout the lifetime of

the program..

Initial values can be given to the variable

Used to create a named constant.

Page 61: Chap3 inheritance
Page 62: Chap3 inheritance

Object class

Java defines a class called Object that is an

implicit superclass of all other classes

All other classes are subclasses of Object

This means that a reference variable of type

Object can refer to an object of any other

class.

Object defines the following methods, which

are available for all objects

Page 63: Chap3 inheritance

Method purpose

Object clone() Creates a new object that is same as the object

being cloned.

boolean equals(Object

obj)

Determines whether one object is equal to

another.

void finalize() Called before unused object to be recycled

int hashCode() Returns the hash code associated with the

invoking object

void notify() Resumes execution of a thread waiting on the

invoking object

void wait() Waits on another thread of execution

String toString() Returns a string that describes the object