05-CCFP4.0_OOP Using Java

Embed Size (px)

DESCRIPTION

fa2

Citation preview

  • OO Programming using Java

    Education, Training and AssessmentWe enable you to leverage knowledge anytime, anywhere!

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

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

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

    2

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    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

    3

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Course Information

    Course Code: CCFP4.0-OOP

    Course Name: OO Programming using Java

    Document Number: OOP-05

    Version Number: V4.0

    4

  • OO Concepts - II

    Education, Training and AssessmentWe enable you to leverage knowledge anytime, anywhere!

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    OO Constructs - II Static Polymorphism

    Method and Constructor Overloading

    Relationships

    Inheritance

    Aggregation

    Association

    Interfaces

    Packages

    6

  • Static Polymorphism

    Education, Training and AssessmentWe enable you to leverage knowledge anytime, anywhere!

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Method Overloading

    Two or more methods in a class can have the same name, if their argument listsare 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

    8

    Guided Activity: Advanced OO Concepts - Assignment 61

    Demo: Advanced OO Concepts - Assignment 62

    Quiz: OO Concepts - Part I - Assignment 63

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Constructor Overloading

    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

    9

    Demo: Advanced OO Concepts Assignment - 64

    Guided Activity: Advanced OO Concepts- Assignment - 65

  • Introduction to Relationships

    10

    Education, Training and AssessmentWe enable you to leverage knowledge anytime, anywhere!

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Relationships

    Few kinds of relationships between classes :

    Generalization and specialization (is-a relationship)

    Aggregation (has-a relationship)

    Association (uses-a relationship)

    11

    Demo: Advanced OO Concepts - Assignment 66

  • Inheritance

    12

    Education, Training and AssessmentWe enable you to leverage knowledge anytime, anywhere!

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Inheritance (1 of 2)

    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 datamembers in the derived class during the creation of derived class object

    13

    Demo: Advanced OO Concepts - Assignment 67

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    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 objectof the base/derived class is created

    If the base class constructor is a parameterized one, it has to be explicitly invoked by thederived 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

    14

    Quiz: Advanced OO Concepts Assignment 68

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    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 ConfidentialConfidential

    Aggregation

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

    16

    Demo: Advanced OO Concepts - Assignment - 69

    classAddress{privateStringaddressLine;publicAddress(StringaddressLine){

    this.addressLine=addressLine;}publicStringgetAddressLine(){

    returnaddressLine;}

    }classCustomer{privateAddressaddress;publicCustomer(Addressaddress){

    this.address=address;}publicAddressgetAddress(){

    returnaddress;}

    }

    classRetail{publicstaticvoidmain(Stringargs[]){

    Addressadd=newAddress(No.333);CustomercustObj=newCustomer(add);//CheckifaddressiscorrectlysavedAddresstemp=custObj.getAddress();System.out.println("Address:");System.out.println(temp.getAddressLine());

    }}

    Stack Heap

    add addressLine No.333

    custObj

    addresstemp

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    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.

    17

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Association Loosely coupled relationship

    18

    Demo: Advanced OO Concepts - Assignment 70

  • Method Overriding

    Education, Training and AssessmentWe enable you to leverage knowledge anytime, anywhere!

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Method Overriding

    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

    20

    Demo: Advanced OO Concepts - Assignment 72

    Guided Activity: Advanced OO Concepts - Assignment 71

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Dynamic Polymorphism (1 of 2)

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

    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 overriddenby 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 NOTbased on the data type of the reference

    This decision is taken at runtime and hence this is known as dynamic binding-linking between the method call and the method definition happens at runtime

    21

    Guided Activity: Advanced OO Concepts - Assignment 73

    BasebObj=newDerived();

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Dynamic Polymorphism (2 of 2)22

    Demo: Advanced OO Concepts - Assignment 74, 75

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Method overloading vs. method overriding23

    Method Overloading Method Overriding

    More than one method having same namebut different argument list and with differentimplementation

    More than one method having the samename and same argument list and withdifferent implementation

    Return type may or may not be different Return type should be the same in theoverridden method and correspondingmethod in the base class

    Overloaded methods can be in the sameclass

    Overriding happens between base andderived class

    Invoking is done based on signature of themethod

    Invoking is done based on the data type ofthe object referred by the reference

    Binding happens at compile time Binding happens at Runtime

  • abstract keyword

    Education, Training and AssessmentWe enable you to leverage knowledge anytime, anywhere!

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    abstract keyword (1 of 2)

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

    An abstract method signifies that its functionality is not defined, but the prototypeis 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., theclass which inherits MUST provide the implementation of the method else it should bedeclared abstract

    There is only the declaration of the method followed by a semicolon

    25

    abstractpublicvoiddisplayCustomerInformation();

    Guided Activity : Advanced OO Concepts - Assignment 76

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    abstract keyword (2 of 2)

    Abstract Class -

    If a class has one or more abstract methods declared inside it, then the class must bedeclared abstract

    An abstract class cannot be instantiated ie. objects cannot be created for an abstractclass but a reference variable of abstract class can be created

    26

    abstractclassCustomer{abstractpublicvoiddisplayCustomerInformation();

    }

    Guided Activity : OO Concepts - Part II Assignment 78

    Demo: Advanced OO Concepts - Assignment 77

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Quizabstract 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();}}

    27

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Food for thought Consider the modified Purchase class diagram

    28

    PurchaseBillbillId:intcustomer:CustomerbillAmount:floattypeOfCustomer:String+Purchase(Customer,float,String)+getBillId():int+getCustomer():Customer+calculateBillAmount(String,float):void+displayBill():void

    The customer reference is placed as an instance variable inside the Purchase class. Depending upon thetype of customer decided during billing time , this customer reference can be made to point to an objectof Regular customer or Privileged Customer. In addition, a variable typeOfCustomer is kept to keep trackof the kind of customer

    This is possible because a base class reference can point to an object of derived type.

    Identifytherelationshipbetween

    CustomerandPurchaseclass?

  • Interfaces

    Education, Training and AssessmentWe enable you to leverage knowledge anytime, anywhere!

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Interfaces

    Interfaces are useful when an unrelated set of classes have a common set of method(s)

    Interface can be defined as follows:

    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

    30

    Guided Activity: Interfaces - Assignment 79

    {//methods}

    Demo: Interfaces - Assignment 80

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Abstract Classes vs. Interfaces31

    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 ConfidentialConfidential

    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

    32

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    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();}}

    33

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    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();}

    }

    34

  • Packages

    Education, Training and AssessmentWe enable you to leverage knowledge anytime, anywhere!

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Method1Using the fully qualified class name

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

    Method2Import the package and use the class name

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

    Packages (1 of 4)

    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

    36

    Guided Activity: Packages - Assignment 81

    Demo: Packages - Assignment 82

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential37

    Built-in-Packages (2 of 4)

    These packages provide the set of classes, interfaces andmethods for the programmer to develop an application in an easierway

    Programmer can reuse everything from the package and saveeffort

    Few examples of built in packages java.lang

    java.io

    java.sql java.awt java.net Java.util

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Packages (3 of 4)38

    Accessibleonlywithintheclassprivate Nokeyword,Accessibleonlywithinthepackagedefault Similartodefaultwiththeadditionthatitisavailabletoallchildclasses;thatis,evenifchildclassisinadifferentpackageprotected

    Accessibletoallpublic

    Accessibleto public protected default privateSame 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 ConfidentialConfidential

    Packages (4 of 4)

    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

    39

    overriddenmethodinchildclass

    Methodinparentclass

    public protected default private

    public Yes No No No

    protected Yes Yes No No

    default Yes Yes Yes No

    private Privatemethodscannot beoverridden

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    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,

    40

    import java.util.Scanner;public class ScannerDemo {

    public static void main(String[] args) {// TODO Auto-generated method stubScanner 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 ConfidentialConfidential

    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?

    41

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Quizclass 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();}}

    42

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Quizabstract 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();}}

    43

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    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

    44

    Demo : Packages - Assignment 83

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Retail Application we have learnt45

    1. Static Polymorphism2. Introduction to Relationships3. Dynamic Polymorphism4. Abstract5. Interface

  • Copyright 2013-2014, Infosys Limited ConfidentialConfidential

    Self-Study46

    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

  • 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 changewithout notice. Infosys acknowledges the proprietary rights of other companies to the trademarks, product names and such other intellectual property rights mentioned in this document. Exceptas 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.

    Thank You