Вы находитесь на странице: 1из 47

OO Programming using Java

Education, Training and Assessment


We enable you to leverage knowledge anytime,
anywhere!

Copyright Guideline
2013 Infosys Limited, Bangalore, India. All Rights Reserved.

Infosys believes the information in this document is accurate as of its publication date; such
information is subject to change without notice. Infosys acknowledges the proprietary rights of
other companies to the trademarks, product names and such other intellectual property rights
mentioned in this document. Except as expressly permitted, neither this documentation nor
any part of it may be reproduced, stored in a retrieval system, or transmitted in any form or by
any means, electronic, mechanical, printing, photocopying, recording or otherwise, without the
prior permission of Infosys Limited and/ or any named intellectual property rights holders
under this document.

Copyright 2013-2014, Infosys Limited

Confidential

Confidential Information
This Document is confidential to Infosys Limited. This document contains information and data that
Infosys considers confidential and proprietary (Confidential Information).
Confidential Information includes, but is not limited to, the following:
Corporate and Infrastructure information about Infosys
Infosys project management and quality processes
Project experiences provided included as illustrative case studies
Any disclosure of Confidential Information to, or use of it by a third party, will be damaging to Infosys.
Ownership of all Infosys Confidential Information, no matter in what media it resides, remains with
Infosys.
Confidential information in this document shall not be disclosed, duplicated or used in whole or in part
for any purpose other than reading without specific written permission of an authorized representative of
Infosys.
This document also contains third party confidential and proprietary information. Such third party
information has been included by Infosys after receiving due written permissions and authorizations from
the party/ies. Such third party confidential and proprietary information shall not be disclosed, duplicated
or used in whole or in part for any purpose other than reading without specific written permission of
an authorized representative of Infosys.

3
Copyright 2013-2014,
Infosys Limited

Confidential

Course Information

Course Code: CCFP4.0-OOP


Course Name: OO Programming using Java
Document Number: OOP-05
Version Number: V4.0

Copyright 2013-2014, Infosys Limited

Confidential

OO Concepts - II

Education, Training and Assessment


We enable you to leverage knowledge anytime,
anywhere!

OO Constructs - II
Static Polymorphism
Method and Constructor Overloading

Relationships
Inheritance
Aggregation
Association

Interfaces
Packages

Copyright 2013-2014, Infosys Limited

Confidential

Static Polymorphism

Education, Training and Assessment


We enable you to leverage knowledge anytime,
anywhere!

Method Overloading
Guided Activity: Advanced OO Concepts - Assignment 61

Two or more methods in a class can have the same name, if their argument lists
are different
Argument list could differ in
Number of parameters
Data type of parameters
Sequence of data type of parameters

Binding of method call to its definition happens at compile time


Demo: Advanced OO Concepts - Assignment 62

Quiz: OO Concepts - Part I - Assignment 63

Copyright 2013-2014, Infosys Limited

Confidential

Constructor Overloading
Demo: Advanced OO Concepts Assignment - 64

Just like other methods, constructors also can be overloaded


Based on constructor invoked during object creation, either the parameterized or
default constructor will be invoked

Guided Activity: Advanced OO Concepts- Assignment - 65

Copyright 2013-2014, Infosys Limited

Confidential

10

Introduction to Relationships

Education, Training and Assessment


We enable you to leverage knowledge anytime,
anywhere!

11

Relationships
Few kinds of relationships between classes :
Generalization and specialization (is-a relationship)
Aggregation (has-a relationship)
Association (uses-a relationship)

Demo: Advanced OO Concepts - Assignment 66

Copyright 2013-2014, Infosys Limited

Confidential

12

Inheritance

Education, Training and Assessment


We enable you to leverage knowledge anytime,
anywhere!

13

Inheritance (1 of 2)
Demo: Advanced OO Concepts - Assignment 67

Concept wherein a class shares some common structure or behavior with one or
more classes
Generalized class also known as parent class or base class or super class
Specialized class also known as child class or derived class or sub class
Types of inheritance
Single level inheritance
Multilevel inheritance
Hierarchical inheritance

Base class constructors are not inherited in the derived class


Base class constructors may need to be invoked to initialize the inherited data
members in the derived class during the creation of derived class object
Copyright 2013-2014, Infosys Limited

Confidential

14

Inheritance (2 of 2)
Base class constructors may be default or parameterized constructors
If the base class constructor is a default one, it is automatically invoked when the object
of the base/derived class is created
If the base class constructor is a parameterized one, it has to be explicitly invoked by the
derived class during the object creation

Base class constructors can be invoked using super keyword


The super keyword can be used to refer members and constructors of a base
class from a derived class
super keyword can also be used to prevent instance variable hiding
Quiz: Advanced OO Concepts Assignment 68

Copyright 2013-2014, Infosys Limited

Confidential

Inheritance protected access specifier


If an instance variable in the base class has the protected access specifier
It can be directly accessed inside the subclasses

This is useful as methods of the child class can access the parent class variables
directly

In UML notation # is used to represent the protected access specifier

Note: More on protected access specifier would be dealt along with packages topic

15

Copyright 2013-2014, Infosys Limited

Confidential

16

Aggregation
Demo: Advanced OO Concepts - Assignment - 69

A simplified version of the demo is provided here to summarize aggregation


classAddress{
privateStringaddressLine;
publicAddress(StringaddressLine){
this.addressLine=addressLine;
}
publicStringgetAddressLine(){
returnaddressLine;
}
}
classCustomer{
privateAddressaddress;
publicCustomer(Addressaddress){
this.address=address;
}
publicAddressgetAddress(){
returnaddress;
}
}

Copyright 2013-2014, Infosys Limited

classRetail{
publicstaticvoidmain(Stringargs[]){
Addressadd=newAddress(No.333);
CustomercustObj=newCustomer(add);
//Checkifaddressiscorrectlysaved
Addresstemp=custObj.getAddress();
System.out.println("Address:");
System.out.println(temp.getAddressLine());
}
}
temp

address

custObj
add

addressLine
No.333

Stack

Heap

Confidential

17

Quiz
A. Consider a scenario of an employee management system.
The employee details stored are empID, empName and
dateOfJoining. The developer creates two classes called
Employee and Date to store the employee details and the date
respectively. What is the relationship between the classes?
B. Write a Java code to implement the above scenario.

Copyright 2013-2014, Infosys Limited

Confidential

18

Association
Loosely coupled relationship

Demo: Advanced OO Concepts - Assignment 70

Copyright 2013-2014, Infosys Limited

Confidential

Method Overriding

Education, Training and Assessment


We enable you to leverage knowledge anytime,
anywhere!

20

Method Overriding
Guided Activity: Advanced OO Concepts - Assignment 71

A child class can modify methods inherited from a parent class


The child class can create a method with different functionality than the parents
method but with the same:
Name
Return type
Argument list and order

This feature is known as Method Overriding


Demo: Advanced OO Concepts - Assignment 72

Copyright 2013-2014, Infosys Limited

Confidential

21

Dynamic Polymorphism (1 of 2)
Guided Activity: Advanced OO Concepts - Assignment 73

A child class(ex. Derived) object can be assigned to a parent class reference(ex.


Base)
BasebObj=newDerived();

The parent class reference can be used to access the child class methods
Only those methods that were originally present in the parent class and later overridden
by the child class can be called in this way
A new method defined in the child class cannot be called using the base class reference

JVM calls a method based on the data type of the object referred by it and NOT
based on the data type of the reference
This decision is taken at runtime and hence this is known as dynamic bindinglinking between the method call and the method definition happens at runtime
Copyright 2013-2014, Infosys Limited

Confidential

22

Dynamic Polymorphism (2 of 2)

Demo: Advanced OO Concepts - Assignment 74, 75

Copyright 2013-2014, Infosys Limited

Confidential

23

Method overloading vs. method overriding


Method Overloading

Method Overriding

More than one method having same name More than one method having the same
but different argument list and with different name and same argument list and with
implementation
different implementation
Return type may or may not be different

Return type should be the same in the


overridden method and corresponding
method in the base class

Overloaded methods can be in the same Overriding happens between base and
class
derived class
Invoking is done based on signature of the Invoking is done based on the data type of
method
the object referred by the reference
Binding happens at compile time

Copyright 2013-2014, Infosys Limited

Binding happens at Runtime

Confidential

abstract keyword

Education, Training and Assessment


We enable you to leverage knowledge anytime,
anywhere!

25

abstract keyword (1 of 2)
Guided Activity : Advanced OO Concepts - Assignment 76

The abstract keyword can be used with method to make it abstract


An abstract method signifies that its functionality is not defined, but the prototype
is known
Abstract methods
Only the signature of the method is specified, no implementation for the method
Used to put some kind of compulsion on the class which inherits from this class. i.e., the
class which inherits MUST provide the implementation of the method else it should be
declared abstract
There is only the declaration of the method followed by a semicolon

abstractpublicvoiddisplayCustomerInformation();

Copyright 2013-2014, Infosys Limited

Confidential

26

abstract keyword (2 of 2)
Abstract Class If a class has one or more abstract methods declared inside it, then the class must be
declared abstract
An abstract class cannot be instantiated ie. objects cannot be created for an abstract
class but a reference variable of abstract class can be created
abstractclassCustomer{
abstractpublicvoiddisplayCustomerInformation();
}
Demo: Advanced OO Concepts - Assignment 77

Guided Activity : OO Concepts - Part II Assignment 78

Copyright 2013-2014, Infosys Limited

Confidential

27

Quiz
abstract class Example{
public void disp(){
System.out.println("disp in Example");
}
public abstract void display();
}
abstract

class Example1 extends Example{


public void display1(){
System.out.println("display in Example1");
}

}
class Example2 extends Example1{
public void display(){
System.out.println("display in Example2");
}
}
class Demo{
public static void main(String args[]){
Example1 obj=new Example1();
obj.display();
}
}
Copyright 2013-2014, Infosys Limited

Confidential

28

Food for thought


Consider the modified Purchase class diagram
PurchaseBill
billId:int
customer:Customer
billAmount:float
typeOfCustomer:String
+Purchase(Customer,float,String)
+getBillId():int
+getCustomer():Customer
+calculateBillAmount(String,float):void
+displayBill():void

Identifythe
relationshipbetween
Customerand
Purchaseclass?

The customer reference is placed as an instance variable inside the Purchase class. Depending upon the
type of customer decided during billing time , this customer reference can be made to point to an object
of Regular customer or Privileged Customer. In addition, a variable typeOfCustomer is kept to keep track
of the kind of customer
This is possible because a base class reference can point to an object of derived type.

Copyright 2013-2014, Infosys Limited

Confidential

Interfaces

Education, Training and Assessment


We enable you to leverage knowledge anytime,
anywhere!

30

Interfaces
Guided Activity: Interfaces - Assignment 79

Interfaces are useful when an unrelated set of classes have a common set of
method(s)
Interface can be defined as follows:
<<Accessspecifier>><<interface>><<interfacename>>{
//methods
}

All the variables are public static final variables by default


All the methods are public and abstract by default
It is represented by the UML symbol
Demo: Interfaces - Assignment 80

Copyright 2013-2014, Infosys Limited

Confidential

31

Abstract Classes vs. Interfaces


Abstract Classes

Interfaces

Can have concrete methods

Can have only abstract methods

Can have variables of any access


specifier

Can have only public static final (constant)


data members

Concrete methods can have any access


specifier

All member methods are public and


abstract by default

A class can extend only one abstract


class

A class can implement any number of


interfaces

Copyright 2013-2014, Infosys Limited

Confidential

32

Quiz
Say true or false
An abstract class may have a non abstract method
If the class has one abstract method then that class should be declared abstract
All the methods of an interface are abstract by default
All the methods of an abstract class are abstract by default
A class can implement any number of interfaces
An object of an interface can be instantiated

Copyright 2013-2014, Infosys Limited

Confidential

33

Quiz
What is the output of the following code snippet?
interface Example{
int num=90;
public abstract void disp();
public abstract void display();
}
class Example1 implements Example{
public void display(){
System.out.println("display in Example1");
}
}
class Demo{
public static void main(String args[]){
Example1 obj=new Example1();
obj.display();
}
}

Copyright 2013-2014, Infosys Limited

Confidential

34

Quiz
What is the output of the following code snippet?
interface Example{
int num=90;
public abstract void disp();
public abstract void display();
}
class Example1 implements Example{
public void display(){
System.out.println("display in Example1");
}
public void disp(){
int num=900;
System.out.println(num);
}
}
class Demo{
public static void main(String args[]){
Example1 obj=new Example1();
obj.display();
obj.disp();
}

Copyright 2013-2014, Infosys Limited

Confidential

Packages

Education, Training and Assessment


We enable you to leverage knowledge anytime,
anywhere!

36

Packages (1 of 4)
Guided Activity: Packages - Assignment 81

In Java, Packages are used for grouping a number of related classes and
interfaces together into a single unit
In other object oriented languages like C++ a similar concept of namespaces exist
Package types Built in and user defined
Accessing Classes from the Packages

Method1

Method2

Using the fully qualified class name

Import the package and use the class name

Eg: java.lang.Math.sqrt(varOne);

Eg: import java.lang.Math;


Math.sqrt(varOne);

Demo: Packages - Assignment 82

Copyright 2013-2014, Infosys Limited

Confidential

Built-in-Packages (2 of 4)
These packages provide the set of classes, interfaces and
methods for the programmer to develop an application in an easier
way
Programmer can reuse everything from the package and save
effort
Few examples of built in packages
java.lang
java.io
java.sql
java.awt
java.net
Java.util

Copyright 2013-2014, Infosys Limited

Confidential
37

38

Packages (3 of 4)

private

Accessibleonlywithintheclass

default

Nokeyword,Accessibleonlywithinthepackage

protected

Similartodefaultwiththeadditionthatitisavailabletoall
childclasses;thatis,evenifchildclassisinadifferentpackage

public

Accessibletoall
Accessibleto

public

protected

default

private

Same class

Yes

Yes

Yes

Yes

All classesinthesamepackage

Yes

Yes

Yes

No

All subclassesinthedifferentpackage

Yes

Yes

No

No

All classesinthedifferentpackage

Yes

No

No

No

Copyright 2013-2014, Infosys Limited

Confidential

39

Packages (4 of 4)
public

protected

default

private

public

Yes

No

No

No

protected

Yes

Yes

No

No

default

Yes

Yes

Yes

No

overriddenmethod
inchildclass

Methodinparentclass

private

Privatemethodscannot beoverridden

Benefits
Logical grouping of classes and interfaces
Avoids name clashes
Provides four level of access specification to the members of a class in a package

Copyright 2013-2014, Infosys Limited

Confidential

40

Scanner class
The java.util.Scanner class is a simple text scanner which can parse primitive
types and strings using regular expressions. To read a string or integer,
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner ob=new Scanner(System.in);
System.out.println("Enter your username: ");
String name=ob.nextLine();
System.out.println("Enter a Number");
int number=ob.nextInt();
System.out.println(name);
System.out.println(number);
}
}
Copyright 2013-2014, Infosys Limited

Confidential

41

Quiz
Consider the following scenario:
Let us consider a Package1 has a public class called class A. class A has the
following member variables:
private int num1
protected int num2
int num3

Let us consider another package Package2 which has a class called class B
which is extended from class A of Package1.
Which of the data members of class A can be accessed in class B?

Copyright 2013-2014, Infosys Limited

Confidential

42

Quiz
class Base{
int basevar;
public void commonMethod(){
System.out.println("Common method of base");
}
}
class Der extends Base{
private void commonMethod(){
System.out.println("Common method of derived");
}
}
class Demo{
public static void main(String args[]){
Der obj=new Der();
obj.commonMethod();
}
}

Copyright 2013-2014, Infosys Limited

Confidential

43

Quiz
abstract class Example{
public void disp(){
System.out.println("disp in Example");
}
public abstract void display();
}
class Example1 extends Example{
private void display(){
System.out.println("display in Example1");
}
}
class Demo{
public static void main(String args[]){
Example obj=new Example1();
obj.display();
}
}

Copyright 2013-2014, Infosys Limited

Confidential

44

Roy and the Retail Application


Roy and team was successful in coming up with the first version of the retail
application

Roy wants you to have a look at the application

Demo : Packages - Assignment 83

Copyright 2013-2014, Infosys Limited

Confidential

45

Retail Application we have learnt


1.
2.
3.
4.
5.

Static Polymorphism
Introduction to Relationships
Dynamic Polymorphism
Abstract
Interface

Copyright 2013-2014, Infosys Limited

Confidential

46

Self-Study
1. Refer to udacity course: https://www.udacity.com/courses
Course name: Introduction to Programming in Java
Lessons: Interfaces and Inheritance

Links: http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism

Copyright 2013-2014, Infosys Limited

Confidential

Thank You

2013 Infosys Limited, Bangalore, India. All Rights Reserved. Infosys believes the information in this document is accurate as of its publication date; such information is subject to change
without notice. Infosys acknowledges the proprietary rights of other companies to the trademarks, product names and such other intellectual property rights mentioned in this document. Except
as expressly permitted, neither this documentation nor any part of it may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, printing,
photocopying, recording or otherwise, without the prior permission of Infosys Limited and/ or any named intellectual property rights holders under this document.

Вам также может понравиться