Escolar Documentos
Profissional Documentos
Cultura Documentos
To revise Object Oriented Programming concepts To introduce Java architecture and the basic syntax of Java To introduce the implementation of object oriented concepts using Java To introduce the Java library To introduce exception handling in Java To introduce annotations in Java To introduce JDBC
LOC 2
References
Herbert Schildt, The Complete Reference, Java J2SE 5 Edition, Tata McGraw Edition Sierra, Kathy and Bates, Bert, Head First Java, 2nd Edition, Shroff Publishers
Software Complexity
There are two categories of software
Software developed for individuals for their own use Industrial strength software normally used by many people
Software Complexity
The development process will also add to the complexity
1. Co-ordination between the onsite and offshore team 2. Version control 3. People management 4. Resolution of issues 5. etc
The following slides explain how programmers use various techniques to manage the complex nature of software development.
All these units need to work on a data item to produce the result
The data need to be global Global data made the code complex
10
An object is a self-contained entity that contains attributes (data) and behaviors (functions)
Car, Telephone, Pen
For using an object one needs to just invoke a method (function) on the object
No need to know the internal details (data) of the object
11
Behavior
Bark Wag Tail Eat
12
Examples
Animal, Human Being, Automobiles, Bank Account, Customer
13
14
Class Car
15
object
class
Class Student name rollNo setName() setRollNo()
Jodie R001
Daria R002
Jane R003
Brittany R004
getMarks()
16
Abstraction (1/2)
The process of exposing the relevant details and hiding the irrelevant details is called Abstraction
Helps simplify the understanding and using of any complex system One does not have to understand how the engine works to drive a car Similarly one does not have to understand the internal implementation of a software object to use it
17
Abstraction (2/2)
Consider a Stack
The Stack can be implemented using an array or a linked list One need not know this to use the Stack object Just invoke the push method and pop method to make the Stack object work
18
Encapsulation
Encapsulate = En + Capsulate; En = In a; Encapsulate = In a Capsule
Localization of information of knowledge within an object. Information hiding A cars dashboard hides the complexity and internal workings of its engine.
19
Typically in a class
State is private (not accessible externally) Behavior is public (accessible externally)
By enforcing this restriction, object oriented programming allows isolation of complexity in a manageable way
20
21
Polymorphism
Refers to an objects ability to behave differently depending on its type
Poly = many morph = form
Method Overloading is a way to achieve polymorphism Practice of using same method name to denote several different operations
22
Polymorphism
For example, consider a class String which is designed to simplify string operations Append functions are overloaded to accept different types of data One Append function appends an integer value to string, another Append function appends a float value
void append(int) void append(float)
The appropriate function will be invoked based on the type of the argument used in the function call Any number of functions can have the same name as long as they differ in any one of the following
Type of arguments Number of arguments Order of arguments
23
UML and UML Class Diagrams Unified Modeling Language (UML) is a set of diagrams which pictorially represent object oriented design UML is extensively used by software engineers to communicate design In OO Design
Pictures are easier to understand than textual explanation
UML Class diagram is a technique to represent classes and their relationships pictorially
24
Some notations in UML + before a member indicates public - before a member indicates private
25
Relationships
Different types of relationships can exist between classes Identifying relationships helps design the objects better
Analogous to relations between entities in RDBMS design
Uses-A
Driver uses a Car
26
27
Summary
Classes and Objects Abstraction Encapsulation Polymorphism UML Class relationships
28
Java Programming
Introduction to Java
Java is a language developed by Sun Microsystems Java was developed initially for consumer devices Now it is a popular platform to develop web based enterprise applications
30
Architecture Neutral/Portable
Example: Java code compiled on Windows can be run on Unix without recompilation Write Once, Run Anywhere
Secure
Built -in security features like absence of pointers
31
Platform Independence
Java is platform independent. A Java program that is written and compiled in one platform can run on any other platform without any recompilation or modification
Write Once Run Anywhere
32
Java Compiler
The source code of Java will be stored in a text file with extension .java The Java compiler compiles a .java file into byte code
Byte code will be in a file with extension .class Languages like C compiles the program into the machine language format of the hardware platform on which it is running Byte Code is NOT in the machine language format of the hardware platform on which the code is compiled The hardware processor cannot understand the byte code
33
JVM (1/2)
The byte code is in the machine language format of a machine known as the Java Virtual Machine or the JVM
Needs a JVM to execute the byte code JVM is not a real machine, it is just a virtual machine; implemented in software
34
JVM (2/2)
JVM is platform dependant; that is there is one JVM for Windows, another one for UNIX, yet another one for Mainframe etc All JVMs accept the same input, the byte code Each JVM interprets the byte code into the machine language format of the platform on which it is running The same byte code can be run on any platform, if the JVM for that platform is available
The JVMs for all platforms are available free (http://java.sun.com/) and hence we say that the byte code runs in all platforms
35
Java Architecture
JVM
Compiler (javac)
36
Save the file as HelloWorld.java Take care; case of file name matters
37
To Compile
Open a command prompt Go to the directory in which the source file is saved Type the following command
javac HelloWorld.java
The Java compiler will convert the source code into the byte code
HelloWorld.class
38
To execute
Use the following command to execute the bytecode
java HelloWorld
39
Java Program(.java)
Java Compiler(javac)
Byte Code(.class)
Interpreter(java)
Interpreter(java)
Interpreter(java)
Win32
Linux
Mac
40
All numeric data types are signed The size of data types remain the same on all platforms
Floating Type
float (4 bytes) double (8 bytes)
41
The char data type in Java is 2 bytes because it uses UNICODE character set to support internationalization UNICODE is a character set which covers all known scripts and language in the world
Logical
boolean (1 byte) (true/false)
42
Comments in Java
A single line comment in Java will start with //
// This is a single line comment in Java
43
44
BEST PRACTICE: Declare a variable in program only when required. Do not declare variables upfront like in C.
45
Local Variables
In Java, if a local variable is used without initializing it, the compiler will show an error
class Sample{ public static void main (String [] args){ int count; System.out.println(count);//Error } }
46
Whenever a larger type is converted to a smaller type, the typecast operator has to be explicitly specified
double d = 10; int i; i = (int) d;
Type cast operator
47
Operators
Operators in Java are very similar to operators in C
Assignment Operators Arithmetic Operators Relational Operators Logical Operators
48
Control Statements
The syntax of the control statements in Java are very similar to that of C language
if if-else for while do-while switch break continue
49
Methods in Java
The syntax of writing methods in Java is similar to that of functions in C Unlike C
All methods in Java should be written inside a class There is no default return type for a Java method
50
Arrays in Java
In Java, all arrays are created dynamically The operator new is used for dynamic memory allocation The following statement creates an array of 5 integers
new int[5]
51
53
Printing a pointer will print the Printing a reference will NOT address stored in it print the address of the object referred by it Pointer arithmetic like incrementing a pointer is valid in the case of a pointer A pointer has to be dereferenced using the * operator to get the value pointed by it We cannot use arithmetic operators on references
A reference is automatically de-referenced to give the data referred by it and no special operator is required for this
54
int [] x = null;
55
56
If x is a reference to an array, x.length will give you the length of the array
The for loops can be set up as follows
57
Multidimensional Arrays
Multidimensional arrays are arrays of arrays. To declare a multidimensional array variable, specify each additional index using another set of square brackets.
int [][] x; //x is a reference to an array of int arrays x = new int[3][4]; /*Create 3 new int arrays, each having 4 elements x[0] refers to the first int array, x[1] to the second etc x[0][0] is the first element of the first array x.length will be 3 x[0].length, x[1].length and x[2].length will be 4 */
58
59
Summary:
Review of Object Oriented Concepts Java architecture The basic constructs in Java Arrays in Java
60
OO Analysis
OO SDLC has three phases
OO Analysis (Identifying classes and their relationships) OO Design (Designing the data members and methods of a class) OO Implementation (Implementing the design using an OOP language)
An easy way to identify the classes are to identify the nouns in the requirements specifications For example, a system to automate an Insurance company will have to manage the information about the Policy Holders
class PolicyHolder
Copyright 2007, Infosys Technologies Ltd
OO Design
Once the class is identified, we have to identify the data members and methods required in the class Data Members
Policy No Name of the Policy Holder Address Details of the Policy Bonus Amount etc
Methods
Set the Policy No Get the Policy No Set the Name of the Policy Holder Get the Name of the Policy Holder
Copyright 2007, Infosys Technologies Ltd
Encapsulation (binding of code and data together) State (data) is hidden and Behavior (methods) is exposed to external world
Classes in Java
public class PolicyHolder{ private int policyNo; private double bonus; //Other Data Members Data Members (State) Methods (Behavior)
public void setPolicyNo(int no){policyNo = no;} public int getPolicyNo(){return policyNo;} public void setBonus(char amount){bonus = amount;} public double getBonus(){return bonus;} //Other Methods }
The main method may or may not be present in a class depending on whether it is a starter class or not
Copyright 2007, Infosys Technologies Ltd
The reference policyHolder can be used for referring to any object of type PolicyHolder
//Declare a reference to class PolicyHolder PolicyHolder policyHolder; //Create a new PolicyHolder object //Make policyHolder refer to the new object PolicyHolder policyHolder = new PolicyHolder();
All the public members of the object can be accessed with the help of the reference
PolicyHolder policyHolder = new PolicyHolder(); policyHolder.setPolicyNo(20); System.out.println(policyHolder.getPolicyNo());
this reference will refer to the object that has invoked the method When the method getPolicylNo is invoked by an object x, the usage of this in this method refers to x
public int getPolicyNo(){ return policyNo; //return this.policyNo; //These statements are similar }
Copyright 2007, Infosys Technologies Ltd
Constructors (1/5)
A constructor is a special method that is called to create a new object
Calling the constructor PolicyHolder policyHolder = new PolicyHolder();
It is not mandatory for the coder to write a constructor for the class It can be seen as a readily available, implicit method in every class
Constructors (2/5)
The coder can write a constructor in a class, if required If a user defined constructor is available, it is called just after the memory is allocated for the object If no user defined constructor is provided for a class, the implicit constructor initializes the member variables to its default values
numeric data types are set to 0 char data types are set to null character(\0) boolean data types are set to false reference variables are set to null
Constructors (3/5)
The user defined constructor is usually used to initialize the data members of the objects to some specific values, other than the default values A constructor method
will have the same name as that of the class will not have any return type, not even void
Constructors (4/5)
public class PolicyHolder{ //Data Members public PolicyHolder(){ bonus = 100; } //Other Methods } User defined Constructo r
Static Polymorphism
Copyright 2007, Infosys Technologies Ltd
void add (int a, int b) void add (int a, float b) void add (float a, int b) void add (int a, int b, float c)
Constructors (5/5)
public class PolicyHolder{ //Data Members public PolicyHolder(){ bonus = 100; } public PolicyHolder(int policyNo, double bonus){ this.policyNo = policyNo; this.bonus = bonus; } //Other Methods } PolicyHolder policyHolder1 = new PolicyHolder(); //policyHolder1.policyNo is 0 and bonus is 100 PolicyHolder policyHolder = new PolicyHolder(1, 200); //policyHolder1.policyNo is 1 and bonus is 200
Copyright 2007, Infosys Technologies Ltd
These variables are de-allocated in a last in first out order as soon as the method terminates
All dynamically allocated arrays and objects are stored in heap
They need not be de-allocated in any specific order They can be garbage collected (removed from the memory) as and when their use is over
} class Test{ public static void main(String [] args){ PolicyHolder policyHolder; policyHolder = new PolicyHolder(); } }
Lifetime of objects (1 of 2)
policy1
1
Policy policy1 = new Policy(); Policy policy2 = new Policy(); The two Policy objects are now living on the heap
policyNo bonus
References: 2 Objects: 2
Policy policy3 = policy2;
policy2
References: 3 Objects: 2
policy2
Lifetime of objects (2 of 2)
policy1
policy3 = policy1;
References: 3 Objects: 2
policy2 = null;
policy2
Active References: 2 null references: 1policy1 Reachable Objects: 1 policy3 Abandoned objects: 1
2 policyNo bonus Null reference policy2
Garbage Collection
In programming languages like C and C++, the programmer has to deallocate all dynamic memory An object that is not referred by any reference variable will be removed from the memory by the garbage collector
Automatic Garbage Collection If a reference variable is declared within a function, the reference is invalidated soon as the function call ends Programmer can explicitly set the reference variable to null to indicate that the referred object is no longer in use
Primitive types are not objects and they cannot be assigned null
Copyright 2007, Infosys Technologies Ltd
Array of Objects
An array of objects is created as follows
PolicyHolder [] policyHolder = new PolicyHolder[3]; /*3 PolicyHolder references policyHolder[0], policyHolder[1] and policyHolder[2] are created and all 3 references are null*/ for(int i = 0; i < policyHolder.length; ++i){ policyHolder[i] = new PolicyHolder(); //Creating PolicyHolder object } for(int i = 0; i < policyHolder.length; ++i){ System.out.println(policyHolder[i].getPolicyNo()); }
The data common to the entire class An int data member total should be declared as static A single copy of total will be shared by all instances of the class
public class PolicyHolder{ private int policyNo; private double bonus; private static int total; //Other Data Members and Methods }
The static variable is initialized to 0, ONLY when the class is first loaded, NOT each time a new instance is made
It is more logical to think of this method as a method of the entire class rather than that of an object The method getTotal() is declared as static
Each time the constructor is invoked and an object gets created, the static variable total will be incremented thus keeping a count of the total no of PolicyHolder objects created
Static methods can access only other static data and methods
Copyright 2007, Infosys Technologies Ltd
A static block helps to initialize the static data members just like constructors help to initialize instance members
Unlike C, the string is of fixed length and memory for the string is managed totally by the String class
Prevents buffer overruns NULL terminator not used in strings String is not a simple array of characters String is immutable
Copyright 2007, Infosys Technologies Ltd
The + operator works with the String class and helps to concatenate other Strings and objects with a String
String s1 = Hello; String s2 = World; String s3 = s1 + s2; //s3 will contain HelloWorld int a = 20; System.out.println(The value of a is + a);
Copyright 2007, Infosys Technologies Ltd
Class Relationships
Has-A
Has-A relationship occurs when a class contains another class as one of its member Consider the class Policy in the insurance domain
Data Members are Premium, Maturity Value etc Methods to Set the Premium, Get the Premium, Set the Maturity Value, Get the Maturity Value etc
Has-A
public class Policy{ private double premium; private double maturityValue; //Other Data public void setPremium(double premium){ this.premium = premium; } public double getPremium(){return premium;} public void setMaturityValue(double maturityValue){ this.maturityValue = maturityValue; } public double getMaturityValue(){return maturityValue;} //Other Methods }
Has-A Relationship
PolicyHolder has a Policy
Policy -premium : double -maturityValue : double +setPremium(in premium : double) : void +getPremium() : double +setMaturityValue(in maturityValue : double) : void +getMaturityValue(in Amount : double) : void
Copyright 2007, Infosys Technologies Ltd
Has-A
public class PolicyHolder{ private Policy policy; //Other Members }
Uses-A
Uses-A relationship occurs when one class interacts with another
Loosely coupled relationship A method of a class creates an object of the other class A method of a class invokes the method on an object of the other class
Examples:
Policy uses Calendar for calculating the maturity date of the policy
Uses-A Relationship
Policy -premium : double -maturityValue : double +setPremium(in premium : double) : void +getPremium() : double +setMaturityValue(in maturityValue : double) : void +getMaturityValue(in Amount : double) : void Uses-A
Calendar
0..*
Is-A
Is-A Relationship or Inheritance occurs when a class is similar to another class
Inheritance (1/3)
Assume that we require a class TermInsurancePolicy
Needs all the features of the class Policy TermInsurancePolicy will have a pre defined number of years before they expire Needs to add an extra data called term and relevant methods No need to write from the scratch
The keyword extends is used in Java to inherit a sub class from a super class
public class TermInsurancePolicy extends Policy{ //Data Members and Methods }
Copyright 2007, Infosys Technologies Ltd
Inheritance (2/3)
The class Policy is known as the
Inheritance (3/3)
public class TermInsurancePolicy extends Policy{ private int term; public void setTerm(int term){ this.term = term; } public int getTerm(){ return term; } public double getBenefit(){ //Calculate benefit based on //premium, maturityValue and term } }
A TermInsurancePolicy object can invoke all the public methods of the class Policy and those that are newly added in TermInsurancePolicy Thus code reusability is achieved
TermInsurancePolicy -term : int +setTerm(in term : int) : void +getTerm() : int +getBenifit() : double
Multi-Level Inheritance
A class can be further inherited from a derived class
The new class inherits all the member of all its ancestor classes
Multiple Inheritance
Concept of a class inheriting from more than one base class
A Hybrid car can inherit from FuelCar and BatteryCar Multiple inheritance is rarely used because of the complexities it brings in
Modern OO languages like Java and C# dont support Multiple Inheritance
More on Inheritance
Any number of sub classes can be created from a base class Consider a class EndowmentPolicy
EndowmentPolicy is a Policy; EndowmentPolicy is extended from Policy Extra data members and methods are added
public class EndowmentPolicy extends Policy{ //Data Members and Methods }
Specialization
Generalization
TermInsurancePolicy -term : int +setTerm(in term : int) : void +getTerm() : int +getBenifit() : double
EndowmentPolicy
Reusability Standardization
The Java library is organized as a number of packages
Summary:
OO SDLC Classes and Objects
Abstraction Encapsulation
Constructors Method Overloading
Polymorphism
Static Members Command Line Arguments Class Relationships
Java Library
Problem (1/5)
Consider the read and write methods of the class Policy that read and write the member data
public class Policy{ //Data Members and Other Methods public void read(){ //Read the premium, maturityValue //and other data } public void write(){ System.out.println("Premium:" + premium); System.out.println("Maturity Value:" + maturityValue); //Write other data } }
Copyright 2007, Infosys Technologies Ltd
Problem (2/5)
The class TermInsurancePolicy also needs similar methods for reading and writing its data members The methods read() and write() can be redefined in the sub class
public class TermInsurancePolicy extends Policy{ private int term; public void read(){ //Read term } public void write(){ System.out.println(term); } //Other Methods }
If x is a TermInsurancePolicy object, the method call x.read() will invoke the read method of class TermInsurancePolicy reading only the term The case of the write() method is also similar The read() and write() methods of the class termInsurancePolicy are overriding the corresponding methods of the class Policy Redefining a base class method in a sub class is called method overriding
Method calls policy.read() and policy.write() will invoke the read method and write method of the TermInsurancePolicy class JVM calls a method based on the data type of the object referred by the reference and NOT based on the data type of the reference This decision is taken at runtime and hence this is known as dynamic binding
Subclasses that extend an abstract class need to provide implementation of all the abstract methods of the base class or declare the subclass also as abstract
Packages
Packages in Java
A package is a collection of related classes and interfaces in Java Packages help in logical grouping of classes and interfaces
All the classes and interfaces that are used for performing I/O operations can be placed in the same package All the classes and interfaces that are used for writing network programs can be placed in the same package
Creating a Package
It would be better to group all the classes and interfaces related to insurance in a package, insurance
Create a folder insurance Place the following program in this folder
Creating a Package
Compile the program
class Policy will be created in a package insurance
The package statement, if existing, should be the very first statement of the file The fully qualified name of a class that is stored in a package is <packagename>.<ClassName>
insurance.Policy
Importing a Class
It is difficult to use the fully qualified name of a class through out the program The import statement can be used to import a class into a program so that the class name need not be fully qualified
import insurance.Policy; class Test{ public static void main(String [] args){ Policy policy = new Policy(); //Policy means insurance.Policy } }
Copyright 2007, Infosys Technologies Ltd
BEST PRACTICE: Import only those classes that are required in your code, do not import the entire package
Sub Packages
A package can in turn contain another sub package To create a sub package policy in insurance
Create a sub folder policy inside the folder insurance Place the following code in the folder policy and compile package insurance.policy; public class Policy{ //Code goes here }
Data Members and Methods can have any of these specifier Classes and Interfaces can have either the public access or the default access
Uses of Packages
Logical grouping of classes and interfaces Avoiding clash of names Provides an extra level of protection to its members
java.io
Classes and interfaces to perform I/O operations
java.util
Utility classes and interfaces like List, Calendar etc
java.awt
Classes and interfaces to create GUI
Summary:
Method Overriding Dynamic Binding and Runtime Polymorphism Abstract classes The final keyword Interfaces Packages
Thank You
The contents of this document are proprietary and confidential to Infosys Technologies Ltd. and may not be disclosed in whole or in part at any time, to any third party without the prior written consent of Infosys Technologies Ltd. 2006 Infosys Technologies Ltd. All rights reserved. Copyright in the whole and any part of this document belongs to Infosys Technologies Ltd. This work may not be used, sold, transferred, adapted, abridged, copied or reproduced in whole or in part, in any manner or form, or in any media, without the prior written consent of Infosys Technologies Ltd.