46
JAVA WORKSHOP JAVA WORKSHOP SESSION – 3 SESSION – 3 PRESENTED BY PRESENTED BY JAYA RAO MTech(CSE) JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF NEWTON’S INSTITUTE OF ENGINEERING ENGINEERING 1

JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Embed Size (px)

Citation preview

Page 1: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

JAVA WORKSHOPJAVA WORKSHOP

SESSION – 3 SESSION – 3

PRESENTED BY PRESENTED BY

JAYA RAO MTech(CSE)JAYA RAO MTech(CSE)NEWTON’S INSTITUTE OF NEWTON’S INSTITUTE OF

ENGINEERINGENGINEERING

11

Page 2: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

22

Session-IIISession-IIIYou learnYou learn

InheritanceInheritanceConstructorsConstructorsMethod overloadingMethod overloadingMethod overrdingMethod overrdingKeywords extends, super,finalKeywords extends, super,finalAbstract classesAbstract classesDynamic method despatchDynamic method despatchPolymorphismPolymorphism

Page 3: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

OOPs revolve around the three concepts:OOPs revolve around the three concepts:

1. Encapsulation1. Encapsulation

2. Polymorphism2. Polymorphism

3. Inheritance3. Inheritance

33

Page 4: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

The three principles of The three principles of OOPOOP

EncapsulationEncapsulation– Objects hide their Objects hide their

functions (functions (methodsmethods) and ) and data (data (instance instance variablesvariables))

InheritanceInheritance– Each Each subclasssubclass inherits all inherits all

variables of its variables of its superclasssuperclass

PolymorphismPolymorphism– Interface same despite Interface same despite

different data types different data types

car

auto-maticmanual

Super class

Subclasses

draw() draw()

Page 5: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

55

InheritanceInheritance A class can A class can extendextend another class, inheriting all another class, inheriting all

its data members and methods while its data members and methods while redefining some of them and/or adding its redefining some of them and/or adding its own.own.

Inheritance implements the “Inheritance implements the “is ais a” ”

relationship between objects.relationship between objects.

Page 6: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Using inheritance, you can create aUsing inheritance, you can create a

general class that defines traits common to a general class that defines traits common to a set of related items. set of related items.

This class can then be inherited by other, more This class can then be inherited by other, more specific classes, each adding those things that specific classes, each adding those things that are unique to it. are unique to it.

In the terminology of Java, a class that is In the terminology of Java, a class that is inherited is called a inherited is called a superclasssuperclass..

The class that does the inheriting is called a The class that does the inheriting is called a subclass.subclass.

66

Page 7: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

77

Page 8: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

88

Inheritance implements the “is a” relationship.Inheritance implements the “is a” relationship.

Not to be confused with embedding (an object Not to be confused with embedding (an object has another object as a part), which represents has another object as a part), which represents

the “the “has a”has a” relationship: relationship:

A sailboat A sailboat is ais a boat boat

A sailboat A sailboat has ahas a sail sail

Page 9: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Using inheritance, you can create aUsing inheritance, you can create a

general class that defines traits common to a general class that defines traits common to a set of related items. set of related items.

This class can then be inherited by other, This class can then be inherited by other, more specific classes, each adding those more specific classes, each adding those things that are unique to it. things that are unique to it.

In the terminology of Java, a class that is In the terminology of Java, a class that is inherited is called a inherited is called a superclasssuperclass..

The class that does the inheriting is called a The class that does the inheriting is called a subclass.subclass.

99

Page 10: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Therefore, a subclass is a Therefore, a subclass is a specialized specialized version of a superclass.version of a superclass.

It inherits all of the instance variables It inherits all of the instance variables and methods defined by the and methods defined by the superclass and adds its own, unique superclass and adds its own, unique elements.elements.

1010

Page 11: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

The new class will be similar to the The new class will be similar to the existingexisting

class, but will have some new class, but will have some new characteristics.characteristics.

1111

Page 12: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

BENEFITSBENEFITS

Inheritance promotes the concept of Inheritance promotes the concept of code reusability. code reusability.

Inheritance  allows Inheritance  allows

a better data analysis,a better data analysis, reduction in development time,reduction in development time, less coding and better performanceless coding and better performance

1212

Page 13: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

1313

subclass

or

derived class

superclass

or

base class

extends

Inheritance (cont’d) Inheritance (cont’d)

Page 14: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

1414

In Java, a subclass can extend only one In Java, a subclass can extend only one superclass.superclass.

In Java, a class can implement several In Java, a class can implement several interfaces — this is Java’s form of interfaces — this is Java’s form of multiple multiple inheritanceinheritance..

Page 15: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

1515

Inheritance (cont’d)Inheritance (cont’d)Game

GameFor2

BoardGame

Chess Backgammon

Solitaire

Page 16: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

extendsextends keyword keyword

1616

The general formThe general form

class class subclass-namesubclass-name extends extends superclass-namesuperclass-name {{

// body of class// body of class

}}

Page 17: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

The following program creates aThe following program creates a

superclass called superclass called A A and aand a

subclass called B.subclass called B.

1717

Page 18: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

class A {class A {

----------;----------;

---------; //super class---------; //super class

}}

Class B extends class A {Class B extends class A {

---------------;---------------;

---------------; //sub class---------------; //sub class

}}

class mainclass {class mainclass {

public static void main(String args[]) {public static void main(String args[]) {

}}1818

Page 19: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

// A simple example of inheritance.// A simple example of inheritance. // Create a superclass.// Create a superclass. class A {class A { int i, j;int i, j; void showij() {void showij() { System.out.println("i and j: " + i + " " + System.out.println("i and j: " + i + " " +

j);j); }} }} // Create a subclass by extending class A.// Create a subclass by extending class A. class B extends A {class B extends A { int k;int k; void showk() {void showk() { System.out.println("k: " + k);System.out.println("k: " + k); }} void sum() {void sum() { System.out.println("i+j+k: " + (i+j+k));System.out.println("i+j+k: " + (i+j+k)); }} }}

1919

Page 20: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

class SimpleInheritance {class SimpleInheritance { public static void main(String args[]) {public static void main(String args[]) { A superOb = new A();A superOb = new A(); B subOb = new B();B subOb = new B();

subOb.showij();subOb.showij(); subOb.showk();subOb.showk();

System.out.println();System.out.println();

System.out.println("Sum of i, j and k in subOb:");System.out.println("Sum of i, j and k in subOb:");

subOb.sum();subOb.sum(); }} }}

2020

Page 21: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

2121

Inheritance (cont’d)Inheritance (cont’d)

An object of a class at the bottom of a An object of a class at the bottom of a hierarchy inherits all the methods of all hierarchy inherits all the methods of all the classes above.the classes above.

Page 22: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Simple Single InheritanceSimple Single Inheritance

The class that is used as a basis for defining a The class that is used as a basis for defining a new class is called a new class is called a parent class (or parent class (or superclass or base class.)superclass or base class.)

••The new class based on the parent class is The new class based on the parent class is called a called a child class (or subclass or derived child class (or subclass or derived class.)class.)

• • In Java, children inherit characteristics from In Java, children inherit characteristics from just one parent.just one parent.

This is called This is called single inheritancesingle inheritance..2222

Page 23: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Single inheritance :Single inheritance :

A derived class with only one A derived class with only one base class is called single base class is called single inheritance.inheritance.

2323

Page 24: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

2424

Multiple inheritanceMultiple inheritance

A derived class with several base A derived class with several base classes is called multiple classes is called multiple inheritanceinheritance

Page 25: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

2525

Page 26: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Multilevel inheritanceMultilevel inheritance

The mechanism of deriving a The mechanism of deriving a class from another derived class class from another derived class is called multilevel inheritance.is called multilevel inheritance.

2626

Page 27: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

2727

Page 28: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Hierarchical Hierarchical inheritanceinheritance One class may be inherited by One class may be inherited by

more than one classes.more than one classes.

This process is known as This process is known as hierarchical inheritancehierarchical inheritance

2828

Page 29: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

2929

Page 30: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Hybrid inheritanceHybrid inheritance

It is a combination of hierarchical It is a combination of hierarchical and multiple inheritance.and multiple inheritance.

3030

Page 31: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

3131

Page 32: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

3232

Page 33: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Using Using supersuper

super has two general forms.super has two general forms.

The first calls the The first calls the superclass’ superclass’ constructorconstructor. .

The second The second is used is used to access to access a member of a member of the superclass that has been the superclass that has been hidden by a hidden by a member of amember of a

subclass. subclass.

3333

Page 34: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Using Using supersuper to Call to Call Superclass ConstructorsSuperclass Constructors

A subclass can call a constructor A subclass can call a constructor method defined by its superclass by use method defined by its superclass by use of theof the

following form of super:following form of super:

supersuper(parameter-list);(parameter-list);

super( ) must always be the first statement executed super( ) must always be the first statement executed inside a subclass’ constructor.inside a subclass’ constructor. 3434

Page 35: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

parameter-list is defined by the parameter-list is defined by the constructor in the superclass. constructor in the superclass.

super(parameter-list) must be the first super(parameter-list) must be the first statement executed inside a subclass' statement executed inside a subclass' constructor.constructor.

3535

Page 36: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Here is a demo for how to use super to Here is a demo for how to use super to call constructor from parent classcall constructor from parent class

See pgm shapessuper1.javaSee pgm shapessuper1.java

3636

Page 37: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Use super to reference members Use super to reference members from parent classfrom parent class

Its general form is:Its general form is:

super.member super.member member can be either a method or an member can be either a method or an

instance variable.instance variable.

See pgm super2.javaSee pgm super2.java3737

Page 38: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

When Constructors Are When Constructors Are CalledCalled In a class hierarchy, constructors are In a class hierarchy, constructors are

called in order of derivation, from called in order of derivation, from superclass to subclass. superclass to subclass.

The following program illustrates when The following program illustrates when constructors are executed:constructors are executed:

See constructorder.javaSee constructorder.java

3838

Page 39: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

What is Method What is Method OverridingOverriding

Method Overriding happens when a method in a Method Overriding happens when a method in a subclass has the subclass has the same name and type signature same name and type signature as a as a method in its superclass.method in its superclass.

When an overridden method is called within a When an overridden method is called within a subclass, it will refer to the method defined in the subclass, it will refer to the method defined in the subclass.subclass.

The method defined by the superclass will be hidden. The method defined by the superclass will be hidden.

See pgm override1.java or shaperssuper2.javaSee pgm override1.java or shaperssuper2.java3939

Page 40: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

super and overridden methodsuper and overridden method

To access the superclass version of an To access the superclass version of an overridden function, you can do overridden function, you can do so by using so by using super. super.

See override2.java or shapessuper2.javaSee override2.java or shapessuper2.java

4040

Page 41: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Method overriding vs Method overriding vs method overloadmethod overload

Method overriding occurs when the Method overriding occurs when the names names and the type signatures of the two methods and the type signatures of the two methods are identical.are identical.

If not, the two methods are overloaded.If not, the two methods are overloaded.

For example, consider this modified version For example, consider this modified version of the preceding example:of the preceding example:

See prg override3.javaSee prg override3.java4141

Page 42: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Dynamic Method Dynamic Method DispatchDispatch

When an overridden method is called When an overridden method is called through a superclass reference, Java through a superclass reference, Java determines which version of that method to determines which version of that method to execute.execute.

Here is an example that illustrates dynamic Here is an example that illustrates dynamic method dispatch: method dispatch:

see dmd.javasee dmd.java

4242

Page 43: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

What are Abstract ClassesWhat are Abstract Classes

You can require that certain methods be You can require that certain methods be overridden by subclasses by specifying overridden by subclasses by specifying the abstract type modifier. the abstract type modifier.

To declare an abstract method, use this To declare an abstract method, use this general form:general form:

abstract type name(parameter-list);abstract type name(parameter-list);

4343

Page 44: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

No method body is present for No method body is present for abstract method.abstract method.

Any class that contains one or Any class that contains one or more abstract methods must also more abstract methods must also be declared abstract.be declared abstract.

4444

Page 45: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

abstract class MyAbstractClass{abstract class MyAbstractClass{

abstract type name(parameter-abstract type name(parameter-list); list);

}} Here is an abstract class, followed by a Here is an abstract class, followed by a

class which implements its abstract class which implements its abstract method.method.

See prg abs1.javaSee prg abs1.java4545

Page 46: JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1

Using abstract Using abstract methods and classesmethods and classes http://www.java-examples.com/ja

va-string-lower-case-example http://www.particle.kth.se/http://www.particle.kth.se/

~lindsey/JavaCourse/Book/Part1/~lindsey/JavaCourse/Book/Part1/Java/Chapter02/exercises.htmlJava/Chapter02/exercises.html

4646