Polymorphism

- Sub-class can override superclass methods for any specific behavior implementation
- JVM dynamically calls appropriate method based on the inheritance hierarchy
- For the same method call the objects behave differently based on implementation
 
- Promotes reuse and design can be extended by adding more sub-classes without 
changing interface definition. Such as getLanguage() method in below example which takes Country as a parameter, so that it can be used for any Country type, such as Japan, America and Korea including any future new Countries. 
======================================================
Example: Polymorphism using method overriding

Description: Code to demonstrate polymorphic behavior in Java using inheritance and method overriding.


Country is superclass of all specific country sub-classes. The method getLanguage() can be overridden by sub-classes of Country class as shown below, where Japan and America are overriding default implementation of getLanguage() method from Country but Korea class is not overriding it. So when caller program (TestPoly) calls getLanguage() on the Country type the JVM will dynamically call appropriate 
getLanguage() method from sub-class, if method is not overridden in sub-class then JVM will call super class's method i.e. Method from Country in case of Korea.


Design: Class Diagram






Source: 

public class TestPoly {
    public static void main(String[] args) {
         Country[] countries = new Country[3];
         countries[0] = new Japan();
         countries[1] = new America();
         countries[2] = new Korea();    
         for (Country country : countries) {
              getCountryInfo(country);
         }
    }
    //method to print country specific information
    public static void getCountryInfo(Country country) {
         System.out.println(country.getLanguage());
    }
}
Output
Japan's National Language is Japanese
America's National Language is English
UN-KNOWN
--------------------------------------------------------
public class Country {   
     //default implementation
     protected String getLanguage() {
          return "UN-KNOWN";
     }
}
--------------------------------------------------------
public class Japan extends Country {   
     @Override
     public String getLanguage() {
          return "Japan's National Language is Japanese";
     }
}
--------------------------------------------------------
public class America extends Country {
     @Override
     public String getLanguage() {
          return "America's National Language is English";
      }
}
--------------------------------------------------------
public class Korea extends Country {


}

Approaching System Development (102L2)

·      Using Object Oriented Methodology for complete Software Application Development 

Start below activities in Inception Phase,

1.     Write brief “Vision” draft about the project
2.     Identify users’ goals and supporting use cases
3.     Write use cases and Supplementary Specification document
a.     Use cases (Ivan Jacobson, 1986)
                                                                 i.     Are stories using system functionality to meet desired system goals
                                                               ii.     Define Use-case model at requirements stage
                                                              iii.     It defines system functionality (what system will do) and environment
                                                              iv.     It includes interactions between Actors and System for realizing related scenarios such as success or alternate scenarios (failure).
                                                               v.     Scenarios yields observable results for particular actor

b.     Supplementary Specification includes,
                                                                 i.     Quality properties (Non Functional Requirements)
                                                               ii.     constraints
1.     Hardware (Linux due to company roadmap)
2.     Software (only from registered vendors)
3.     Development tools (eclipse)
                                                              iii.     Internationalization and Localization
                                                              iv.     Licensing and compliance
                                                               v.     Business rules
                                                              vi.     Business Contingency plan
                                                            vii.     Users, Installation manual and Help
                                                           viii.     Standard references (development, test, release)

4.     Refine the Vision during next iterations and phases
5.     Create Software Development Plan

Keep refining all above activities in the further phases

Start below activities in Elaboration Phase,

1.     Create Domain Model using Use case and Vision
2.     Write software architecture document
3.     Create Implementation Model
4.     Create Test plan

·      Online Banking System (ATM like system)
o   Requirements
Automate existing manual banking functions to serve Prospects and Customers efficiently and cost effectively. The scope is limited to below functions under Phase-I of this project.

§  Scope :
·      Customer registration system
·      Account transactions includes : deposit, withdrawal, transfer
·      Security management includes : User Authentication and maintenance
·      Some features will be available using web or mobile clients
o   Portfolio Analysis
o   Money Transfer
·      Transaction audit facility for Auditors and Customers

§  Use-case Model




§  Use-case Goals

Use case
Description
Manage Users
User data maintenance and security information will be managed by System Administrator
Authenticate Users
Authenticate Customer login information using existing security service
Money Deposit
Customer does money deposit which finally updates core banking system
Money Withdrawal
Customer does money withdrawal which finally updates core banking system
Money Transfer
Customer does money transfer to other bank accounts  which finally updates core banking system
Transaction Analysis
Customer and Auditor can view account transactions
New Account Registration
Prospect submit form to open new account with the bank which will be authorized or rejected by bank manager


o   Domain Model



o   Build Relationship between Domain Objects

§  Class Diagram



o   Add responsibilities
§  Add methods to each identified object
o   Add System Specific Objects
§  Such as TransactionManager above
o   Re-define objects relationship if necessary
o   Use MVC and layer components
o   Define non-functional requirements (Quality Properties)
§  HA (High Availability) and Performance requirements
§  Security Model
§  Internationalization and Localization
o   Do implementation using Java along with Unit test cases (JUnit).
o   Build GUI presentation layer.

{*Properly use Abstraction, Inheritance, Encapsulation and Polymorphism principles}


Object and Class

1) Object and Class
Class is template to create objects and represents classification of objects such as Employee, which is a class for the objects such as “Tom”, “Joe”, “Hanako”

2) OO-Analysis
            - Break the requirements into smaller problems (decompose the requirements)
            - Try to understand “WHAT” is require instead of “HOW” to implement
- Create conceptual domain model (only consider domain specific objects
   and  not system specific)

Such as in case of  our “Online Banking System” (OBS) Project following is a conceptual design (domain model)

3) OO-Design
o   For each identified object find out how they will cooperate and collaborate with each other to understand the relationship between them.

o   Then assign responsibility by adding properties and methods (behavior) to each object

o   Add helper objects (system specific and not business specific)
Such as TransactionManager

4) OO-Implementation:
o   Implement the design using specific OO Language, such as Java
-       Create new project in eclipse : OnlineBankingSystem
o   Create class : Customer

public class Customer {
       private String lastName;
       private String firstName;

       public String getLastName() {
              return lastName;
       }
       public void setLastName(String lastName) {
              this.lastName = lastName;
       }
       public String getFirstName() {
              return firstName;
       }
       public void setFirstName(String firstName) {
              this.firstName = firstName;
       }
}

Application : Calculator (For 2 Numbers) (102L1)


Requirements:
Create Calculator Application to have following functionality,
- Add 2 numbers
- Subtract 2 numbers
- Divide 2 numbers  
- Multiply 2 numbers


- Take command line input for 2 numbers
- User can enter option based on the menu as shown below,

Menu 
(1=Add, 2=Sub, 3=Div, 4=Mul )


Design:

Implementation:
[CalculatorApp.java]
import java.util.Scanner;

public class CalculatorApp {

    public static void main(String[] args) {



        //read command line arguments from the command line while running this application
        double n1 = Double.parseDouble(args[0]);  //first number
        double n2 = Double.parseDouble(args[1]);  //second number
        

        //use to get user input for operation
        Scanner scan = new Scanner(System.in);

    
        System.out.println("Menu ");
        System.out.println("(1=Add, 2=Sub, 3=Div, 4=Mul )");

        int option = scan.nextInt();
 
        CalculatorApp appC = new CalculatorApp();

        switch (option) {
        case 1 :
            appC.add(n1, n2);
            break;

        case 2 :
            appC.sub(n1, n2);
            break;

        case 3 :
            appC.div(n1, n2);
            break;
        case 4 :
            appC.mul(n1, n2);
            break;

        default :
            System.out.println("Invalid option.");
        }
 
    } //end of main() method

    //Method to add two numbers and display results
    public void add(double n1, double n2) {
        System.out.println("Adding...");
        double result = n1 + n2;
        System.out.println(result);
    }

    
 //Method to subtract two numbers and display results    

    public void sub(double n1, double n2) {
        System.out.println("Subtracting...");
        double result = n1 - n2;
        System.out.println(result);
    }

    //Method to divide two numbers and display results
    public void div(double n1, double n2) {
        System.out.println("Dividing...");
        double result = n1 / n2;
        System.out.println(result);
    }

   //Method to multiply two numbers and display results
    public void mul(double n1, double n2) {
        System.out.println("Multiplying...");
        double result = n1 * n2;
        System.out.println(result);
    }

}



Testing:
=============How to Compile using java command line without Eclipse
javac CalculatorApp.java
The above command will compile CalculatorApp.java to CalculatorApp.class
=============How to Run using Command prompt (such as dos/unix/linux) 
java CalculatorApp 1 2
The above command will run CalculatorApp application with 2 arguments (Number1 and Number2)
=============Output: For Add option [other 3 options (Sub, Div, Mul) ]
Menu 
(1=Add, 2=Sub, 3=Div, 4=Mul )


1
Adding...
3.0

Exception Handling (try...catch...finally)


The try...catch block is mainly use to handle exceptions in java as shown below.

First block : try

Second block : catch
Third block (optional): finally

Source: 
TestException.java


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class TestException {

    public static void main(String[] args) {
        try {
       
            Scanner scanner = new Scanner(new File("ccc"));
       
        } catch (FileNotFoundException exception) {


            exception.printStackTrace();
            System.out.println("Please contact sysadmin. 5111");


        } finally {

            //close any database or other resources, as this block will be executed irrespective of any exceptions or not in above 2 blocks
        }
   
        System.out.println("Thank you.");

    }

}



As the ccc file is not available the above program throws exception of FileNotFoundException type

File Handling


File Writer 


How to use existing Java API for writing data to external file for persistance.
Source: TestFileWriter.java


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class 
TestFileWriter {
    public static void main(String[] args) {
    try {
            FileWriter writer = new FileWriter("c:/citydata.txt", true); //set true for append mode
            BufferedWriter bufferedWriter =new BufferedWriter(writer);
            bufferedWriter.write("Tokyo");
            bufferedWriter.write(",");
            bufferedWriter.write("New York");
            bufferedWriter.write(",");
            bufferedWriter.write("Colombo");
            bufferedWriter.write(",");
            bufferedWriter.write("Korea");
            bufferedWriter.write("\n");

            bufferedWriter.flush();
            bufferedWriter.close();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output
After running above program check for creation of c:/citydata.txt with following contents


Tokyo, New York, Colombo, Korea
=================================================


File Reader 


How to use existing Java API for reading data from external file.
Source: TestFileReader.java

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;

public class 
TestFileReader {
    public static void main(String[] args) {
        File file = new File("c:/citydata.txt");
        try {
            Scanner scan = new Scanner(file);
            while (scan.hasNext()) {
                System.out.println(scan.nextLine());
            }       
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

Output
Tokyo, New York, Colombo, Korea