Você está na página 1de 157

Course Objectives

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

Course Agenda (1/2)


LOC 1
Object Oriented Concepts The Java Architecture The basic constructs in Java Arrays OO SDLC Classes and Objects Constructors Method Overloading Static Members Command Line Arguments Class Relationships

LOC 2

Course Agenda (2/2)


LOC 3
Method Overriding Abstract classes Dynamic Binding and Runtime Polymorphism The final keyword Packages The Java Library Exception Handling

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

What is Java and where is Java being used?


Java is a very powerful OO programming language developed by Sun Microsystems Java is widely used for developing web applications Java is the programming language used for developing Enterprise Applications using the JEE Platform

Object Oriented Programming A Quick Revision

Copyright 2007, Infosys Technologies Ltd

Software Complexity
There are two categories of software
Software developed for individuals for their own use Industrial strength software normally used by many people

Industrial strength software is very complex in nature because of several reasons


Numerous Business rules (Functional Requirements) Non-Functional Requirements like Usability, Performance, Reliability etc Complexity due to development process

Software Complexity
The development process will also add to the complexity

Complexity due to Development Process

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.

Ways to handle Software Complexity


Unstructured Programming
Use of goto statements Lengthy code with no modularity As size increases, code becomes more complex to maintain

Procedural Programming or Structured Programming was introduced to handle software complexity


Brought in Modularity in coding, enhancing maintainability Complexity made manageable by hiding complexity inside functions (Concept of APIs) Introduced the concept of structures (also known as data structures)

Limitations of Structured Programming


In structured programming, focus is on the algorithm and importance is given to the procedure (logic) and not to the data on which these procedures operate The entire problem was divided into a number of smaller units
Functions/Procedures

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

As the code size grows, maintaining code becomes difficult

10

Object Oriented Programming


Object Oriented Programming
The entire program is visualized as a number of objects interacting with each other

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

State and Behavior


Example: Car object
State
Current Speed Current Gear Engine State (Running, Not Running)

Example: Dog Object


State
Color Breed Activity (Barking/Not barking) Tail Activity (Wagging/Not Wagging)

Behavior (Acts on the object and changes state)


Slow down Accelerate Stop Switch Off Engine Start Engine

Behavior
Bark Wag Tail Eat

12

What is a Class? (1/3)


A Class
Is a blue print used to create objects. Is a software template that defines the methods and variables to be included in a particular kind of Object.

Examples
Animal, Human Being, Automobiles, Bank Account, Customer

13

What is a Class? (2/3)


A class contains state and behavior State (Member Variables)
Variables defined inside the class Not exposed to external world

Behavior (Member Methods)


Functions defined inside the class Behavior exhibited by the class to external world Exposed to external world

An object is an instance of a class

14

What is a Class? (3/3)

Class Car

15

Example: Objects and Classes

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

Encapsulation (Data Hiding)


Process of hiding the members from outside the class Implemented using the concept of access specifiers
public, private etc.

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

Encapsulation (Data Hiding)


In a class Stack, the data could be stored in an array which will be private The methods push and pop will be public
A program cannot access the array directly from outside the class A program can access the array indirectly through the push and pop methods

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

Representing a class in UML Class Diagrams

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

There are 3 types of relationships Has-A (or Part-Of)


Car has an Engine

Uses-A
Driver uses a Car

Is-A (or Kind-Of)


Trainee is an Employee

26

Can you answer these questions?


How is structured programming different from object oriented programming? What are classes and objects? What is abstraction? What is encapsulation? What is polymorphism? What is UML? What are the relationships that can exist between classes?

27

Summary
Classes and Objects Abstraction Encapsulation Polymorphism UML Class relationships

28

Java Programming

Copyright 2007, Infosys Technologies Ltd

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

Salient Features of Java


Object Oriented Simpler language
Compared to earlier OO languages like C++, it is simple Designed considering the pitfalls of earlier languages

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

Source File (HelloWorld.java)

JVM
Compiler (javac)

Machine Code or Byte code (HelloWorld.class)


Operating System Hardware

36

A Sample Java Application


The following program can be created using any text editor
public class HelloWorld{ public static void main(String [] args){ System.out.println(Hello World!); } }

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

Compilation & Execution

Java Program(.java)

Java Compiler(javac)

Byte Code(.class)

Interpreter(java)

Interpreter(java)

Interpreter(java)

Win32

Linux

Mac

40

Primitive Data Types in Java


Integer Types
byte (1 byte) short (2 bytes) int (4 bytes) long (8 bytes)

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

Primitive Data Types in Java


Textual
char (2 bytes)

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

A multi line comment starts with a /* and ends with a */

/* This is a multi line comment in Java */

43

Variables in Java (1/2)


Declaring and using primitive data types is Java similar to that of C
int count; int max=100;

44

Variables in Java (2/2)


Unlike C, in Java variables can be declared anywhere in the program
int i = 10; System.out.println(Program starts here); int j = 20; for (int count=0; count < max; count++) { int z = count * 10; }

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

Typecasting of primitive data types


Variable of smaller capacity can be assigned to another variable of bigger capacity without any explicit typecasting
int i = 10; double d; d = i;

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]

The above statement returns a reference to the newly created array


References in Java are very similar to pointers in C

51

Reference variables in Java (1/4)


Reference variables are used in Java to store the references of the objects created by the operator new Any one of the following syntax can be used to create a reference to an int array
int x[]; int [] x;

The reference x can be used for referring to any int array


//Declare a reference to an int array int [] x; //Create a new int array and make x refer to it x = new int[5];
52

Reference variables in Java (2/4)


The following statement also creates a new int array and assigns its reference to x
int [] x = new int[5];

In simple terms, reference can be seen as the name of the array

53

Reference variables in Java (3/4)


Even though we can think of Java references as C pointers, their usages are different Pointers References

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

Reference Types in Java (4/4)


A reference type can be assigned null to show that it is not referring to any object
null is a keyword in Java

int [] x = null;

55

Initializing an array in Java


An array can be initialized while it is created as follows
int [] x = {1, 2, 3, 4}; char [] c = {a, b, c};

56

The length of an array


Unlike C, Java checks the boundary of an array while accessing an element in it
Java will not allow the programmer to exceed its boundary

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

for(int i = 0; i < x.length; ++i){ x[i] = 5; }

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

Can you answer these questions?


How is Java made platform neutral? What is a reference variable in Java?

59

Summary:
Review of Object Oriented Concepts Java architecture The basic constructs in Java Arrays in Java

60

Classes and Objects in Java

Copyright 2007, Infosys Technologies Ltd

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

Access Modifiers private and public


Data members are usually kept private

It is accessible only within the class


The methods which expose the behavior of the object are kept public Key feature of OOP

Encapsulation (binding of code and data together) State (data) is hidden and Behavior (methods) is exposed to external world

Copyright 2007, Infosys Technologies Ltd

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

Creating Objects in Java (1/2)


In Java, all objects are created dynamically

The operator new is used for dynamic memory allocation


The following statement creates an object of the class Student
new PolicyHolder()

The above statement returns a reference to the newly created object

Copyright 2007, Infosys Technologies Ltd

Creating Objects in Java (2/2)


The following statement creates a reference to the class PolicyHolder
PolicyHolder policyHolder;

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

Copyright 2007, Infosys Technologies Ltd

Invoking methods in a class


The following statement also creates a new PolicyHolder object and assigns its reference to policyHolder
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());

The reference can be seen as the name of an object

Copyright 2007, Infosys Technologies Ltd

The this Reference (1/2)


The methods in a class have a reference called this

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

this Reference (2/2)


The this reference can be used in some cases to improve the readability of a program
public class PolicyHolder{ private int policyNo; private double bonus; //Other Data Members public void setPolicyNo(int policyNo){this.policyNo = policyNo;} public int getPolicyNo(){return policyNo;} public void setBonus(char bonus){this.bonus = bonus;} public double getBonus(){return bonus;} //Other Methods }

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

Copyright 2007, Infosys Technologies Ltd

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

Copyright 2007, Infosys Technologies Ltd

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

Copyright 2007, Infosys Technologies Ltd

Constructors (4/5)
public class PolicyHolder{ //Data Members public PolicyHolder(){ bonus = 100; } //Other Methods } User defined Constructo r

PolicyHolder policyHolder = new PolicyHolder(); //policyHolder.bonus is initialized to 100

Copyright 2007, Infosys Technologies Ltd

Method Overloading (1/3)


Two or more methods in a Java class can have the same name, if their argument lists are different Argument list could differ in

- No of parameters - Data type of parameters - Sequence of parameters


This feature is known as Method Overloading

Copyright 2007, Infosys Technologies Ltd

Method Overloading (2/3)


void print(int i){ System.out.println(i); } void print(double d){ System.out.println(d); } void print(char c){ System.out.println(c); }

Calls to overloaded methods will be resolved during compile time

Static Polymorphism
Copyright 2007, Infosys Technologies Ltd

Method Overloading (3/3)


Overloaded methods

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)

void add (int a, float b) int add (int a, float b)

Not overloading. Compiler error.

Copyright 2007, Infosys Technologies Ltd

Overloading the Constructors


Just like other methods, constructors also can be overloaded The constructor without any parameter is called a default constructor

Copyright 2007, Infosys Technologies Ltd

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

Memory Allocation (1/2)


All local variables are stored in a stack

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

Copyright 2007, Infosys Technologies Ltd

Memory Allocation (2/2)


public class PolicyHolder{ private int policyNo; private double bonus; //Other Data Members public void sample(int x){ int y; //More Statements } //More Methods
Data members of the class are stored in the heap along with the object. Their lifetime depends on the lifetime of the object

Local variables x and y are stored in the Stack

} class Test{ public static void main(String [] args){ PolicyHolder policyHolder; policyHolder = new PolicyHolder(); } }

Local variable policyHolder is stored in the Stack

Dynamic objects will be stored in the heap

Copyright 2007, Infosys Technologies Ltd

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

heap 2 policyNo bonus

References: 2 Objects: 2
Policy policy3 = policy2;

policy2

References: 3 Objects: 2

policy1 1 2 policy3 policyNo bonus policyNo bonus heap

policy2

Copyright 2007, Infosys Technologies Ltd

Lifetime of objects (2 of 2)
policy1

policy3 = policy1;

1 policy3 2 policyNo bonus policyNo bonus heap

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

1 policyNo bonus heap

This object can be garbage collected (Can be Removed from memory)

Copyright 2007, Infosys Technologies Ltd

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

Copyright 2007, Infosys Technologies Ltd

Object as Method Arguments and Return Types (1/2)


Objects and arrays can be passed to a method by passing their references as arguments Similarly, they can be returned from a method by returning their references
public class PolicyHolder{ //Data Members and Other Methods public boolean isSame(PolicyHolder policyHolder){ return this.policyNo == policyHolder.policyNo; } } if (policyHolder1.isSame(policyHolder2)){ //Statements }

Copyright 2007, Infosys Technologies Ltd

Object as Method Arguments and Return Types (2/2)


public class PolicyHolder{ //Data Members and Other Methods public PolicyHolder getObject(){ PolicyHolder policyHolder = new PolicyHolder(); policyHolder.policyNo = policyNo; policyHolder.bonus = bonus; //More Statements return policyHolder; } } policyHolder2 = policyHolder1.getObject();

Copyright 2007, Infosys Technologies Ltd

The static keyword


The static keyword can be used in 3 scenarios:

For class variables For methods For a block of code

Copyright 2007, Infosys Technologies Ltd

Static Data Members


Static data is a data that is common to the entire class Assume that the class PolicyHolder wants to keep track of the total number of Policy Holders

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

Copyright 2007, Infosys Technologies Ltd

Static Methods (1/3)


Static method is a method that is common to the entire class Consider a method getTotal() in the class PolicyHolder that returns the value of the static data member total

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

Copyright 2007, Infosys Technologies Ltd

Static Methods (2/3)


public class PolicyHolder{ private int policyNo; private double bonus; private static int total; //Other Data Members and Methods public PolicyHolder(){ ++total; //Other Statements } public static int getTotal(){ return total; } }

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

Copyright 2007, Infosys Technologies Ltd

Static Methods (3/3)


Static methods are invoked using the syntax <ClassName.MethodName>
System.out.println(PolicyHolder.getTotal()); //Prints 0 //A static method can be invoked without creating an object PolicyHolder policyHolder1 = new PolicyHolder (); System.out.println(PolicyHolder.getTotal()); //Prints 1 PolicyHolder policyHolder2 = new PolicyHolder (); System.out.println(PolicyHolder.getTotal()); //Prints 2

Static methods can access only other static data and methods
Copyright 2007, Infosys Technologies Ltd

The Static Block


The static block is a block of statement inside a Java class that will be executed when a class is first loaded
class Test{ static{ //Code goes here } }

A static block helps to initialize the static data members just like constructors help to initialize instance members

Copyright 2007, Infosys Technologies Ltd

Strings in Java (1/3)


String is a system defined class in Java Declaring Hello World in code will create an object of type string with data Hello World and returns a reference to it.
System.out.println(Hello World);

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

Strings in Java (2/3)


A String object can be created without the new operator
String s = Java;

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

Can you answer these questions?


What is a this reference? What are Constructors? What is method overloading? What is Automatic Garbage Collection in Java? What are the uses of the keyword static?

Copyright 2007, Infosys Technologies Ltd

Class Relationships

Copyright 2007, Infosys Technologies Ltd

Relationships between Classes


Different types of relationships can exist between classes Identifying relationships helps in understanding and designing the objects better

Analogous to relations between entities in RDBMS design


There are 3 types of relationships

Has-A (or Part-Of) Uses-A Is-A (or Kind-Of)

Copyright 2007, Infosys Technologies Ltd

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

Copyright 2007, Infosys Technologies Ltd

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 }

Copyright 2007, Infosys Technologies Ltd

Has-A Relationship
PolicyHolder has a Policy

Has-A relationship is represented with a diamond headed line in UML

The class PolicyHolder has a Policy object as a member variable

Has a PolicyHolder -policy : Policy


Part of

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 }

Copyright 2007, Infosys Technologies Ltd

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

Copyright 2007, Infosys Technologies Ltd

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..*

Copyright 2007, Infosys Technologies Ltd

Is-A
Is-A Relationship or Inheritance occurs when a class is similar to another class

A class is a different type of another class

Copyright 2007, Infosys Technologies Ltd

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

super class base class parent class


The class TermInsurancePolicy is known as

sub class derived class child class

Copyright 2007, Infosys Technologies Ltd

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 } }

Copyright 2007, Infosys Technologies Ltd

The protected Access


The method getBenefit() needs to access the data members premium and maturityValue of the class Policy A class member that has the protected access specifier can be accessed by the sub classes also

maturityValue and premium should be declared as protected


public class Policy{ protected double premium; protected double maturityValue; //Other Members }

Copyright 2007, Infosys Technologies Ltd

Creating the sub class Object


TermInsurancePolicy policy = new TermInsurancePolicy(); policy.setPremium(100); policy.setMaturityValue(5000); policy.setTerm(36); System.out.println(policy.getBenefit());

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

Copyright 2007, Infosys Technologies Ltd

Is-A Relationship - Inheritance


Policy -premium : double -maturityValue : double +setPremium(in premium : double) : void +getPremium() : double +setMaturityValue(in maturityValue : double) : void +getMaturityValue(in Amount : double) : void

TermInsurancePolicy -term : int +setTerm(in term : int) : void +getTerm() : int +getBenifit() : double

Note: Inheritance is represented by a triangle head arrow in UML Class diagrams


Copyright 2007, Infosys Technologies Ltd

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

Copyright 2007, Infosys Technologies Ltd

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

Copyright 2007, Infosys Technologies Ltd

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 }

Copyright 2007, Infosys Technologies Ltd

Generalization and Specialization


To use inheritance One has to identify the similarities in different classes Move common data and methods to base class Generalization: Process of identifying the similarities among different classes class Policy represents generalization Common data and methods of all types of policies are in Policy class Specialization: Process of creating classes for specific need from a common base class Derived classes TermInsurancePolicy and EndowmentPolicy represent specialization Specific functionality has been achieved by extending the Policy class

Copyright 2007, Infosys Technologies Ltd

Generalization and Specialization - Example


Policy -premium : double -maturityValue : double +setPremium(in premium : double) : void +getPremium() : double +setMaturityValue(in maturityValue : double) : void +getMaturityValue(in Amount : double) : void

Specialization

Generalization

TermInsurancePolicy -term : int +setTerm(in term : int) : void +getTerm() : int +getBenifit() : double

EndowmentPolicy

Copyright 2007, Infosys Technologies Ltd

Can you answer these questions?


What is a protected access? What is multilevel inheritance? What is Generalization and Specialization in inheritance?

Copyright 2007, Infosys Technologies Ltd

The Java Library


The Java library contains a number of useful classes and interfaces

Reusability Standardization
The Java library is organized as a number of packages

Copyright 2007, Infosys Technologies Ltd

Summary:
OO SDLC Classes and Objects

Abstraction Encapsulation
Constructors Method Overloading

Polymorphism
Static Members Command Line Arguments Class Relationships

Has A Uses A Is A (Inheritance)

Java Library

Copyright 2007, Infosys Technologies Ltd

Method Overriding and Dynamic Binding

Copyright 2007, Infosys Technologies Ltd

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 }

Copyright 2007, Infosys Technologies Ltd

Method Overriding (1/4)


The class TermInsurancePolicy has 4 methods
read() and write() defined in the class Policy read() and write() defined in the class Student

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

Copyright 2007, Infosys Technologies Ltd

Method Overriding (2/4)


The read() method of the class TermInsurancePolicy should first call the read() method of the class Policy to read the premium, maturityValue etc before reading the term The write() method of the class TermInsurancePolicy should first call the write() method of the class Policy to write the premium, maturityValue etc before writing the term An overriding method can call an overridden method using the syntax super.methodName()

Copyright 2007, Infosys Technologies Ltd

Method Overriding (3/4)


public class TermInsurancePolicy extends Policy{ private int term; public void read(){ super.read(); //Read term } public void write(){ super.write(); System.out.println(term); } //Other Methods }
Copyright 2007, Infosys Technologies Ltd

Dynamic Binding (1/4)


A reference to a super class can refer to a sub class object
Policy policy = new TermInsurancePolicy()

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

Copyright 2007, Infosys Technologies Ltd

Dynamic Binding (2/4)


Consider the class EndowmentPolicy
The read and write methods are overridden public class EndowmentPolicy extends Policy{ //Data Members and Method public void read(){ super.read(); //Read other data members } public void write(){ super.write(); //Write other data members } }

Copyright 2007, Infosys Technologies Ltd

Dynamic Binding (3/4)


The following program chooses a TermInsurancePolicy or EndowmentPolicy ate runtime
char choice; //Read choice, T for TermInsurancePolicy, E for EndowmentPolicy if (choice == T){ TermInsurancePolicy tiPolicy = new TermInsurancePolicy(); tiPolicy.read(); tiPolicy.write(); } else{ EndowmentPolicy ePolicy = new EndowmentPolicy(); ePolicy.read(); ePolicy.write(); }

Copyright 2007, Infosys Technologies Ltd

Dynamic Binding (4/4)


The following program does the same work in a better way
char choice; Policy policy; if (choise == T){ policy = new TermInsurancePolicy(); } else{ policy = new EndowmentPolicy(); } policy.read(); //Calls the read of TermInsurancePolicy or EndowmentPolicy //Decided at runtime policy.write(); //Calls the write of TermInsurancePolicy or EndowmentPolicy //Decided at runtime

Copyright 2007, Infosys Technologies Ltd

Runtime Polymorphism (1/2)


In the above program, the same command policy.read() is used to read a TermInsurancePolicy or EndowmentPolicy
Same command invokes different methods based on the context Polymorphism

Decision on which method is to be invoked is taken at runtime


Runtime polymorphism

Copyright 2007, Infosys Technologies Ltd

Runtime Polymorphism (2/2)


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

Copyright 2007, Infosys Technologies Ltd

Static Vs Dynamic Polymorphism


Static Function Overloading - More than one method having same name but differing in argument list Resolved during compilation time Dynamic Function Overriding - keeping the signature and return type same, method in the base class is redefined in the derived class Resolved during run time Which method to be invoked is decided by the object that the reference points to and not by the type of the reference

Copyright 2007, Infosys Technologies Ltd

Can you answer these questions?


What is method overriding? How can we achieve runtime polymorphism in Java?

Copyright 2007, Infosys Technologies Ltd

Abstract Classes and Interfaces

Copyright 2007, Infosys Technologies Ltd

Abstract Class (1/4)


Assume that the insurance company has only two kinds of policies TermInsurancePolicy and EndowmentPolicy The class Policy is created for
reusing the common data and methods grouping TermInsurancePolicy and EndowmentPolicy into a family referring any kind of Policy objects using a Policy reference and achieving runtime polymorphism

Copyright 2007, Infosys Technologies Ltd

Abstract Class (2/4)


Consider the method getBenefit() in the class Policy
Benefit is calculated in each of the sub class in a totally different way The getBenefit() method of class Policy will not have any body A method without a body is known as an abstract method and qualified by the keyword abstract public abstract double getBenefit();

Copyright 2007, Infosys Technologies Ltd

Abstract Class (3/4)


A class that has at least one abstract method is known as an abstract class and should be qualified using the keyword abstract
public abstract class Policy{ //Other Data and Methods public abstract double getBenefit(); }

Abstract classes cannot be instantiated


They are used as base classes for other classes

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

Copyright 2007, Infosys Technologies Ltd

Abstract Class (4/4)


public class TermInsurancePolicy extends Policy{ //Other Data and Methods public double getBenefit(){ //Code goes here } } public class EndowmentPolicy extends Policy{ //Other Data and Methods public double getBenefit(){ //Code goes here } }
Copyright 2007, Infosys Technologies Ltd

Uses of Abstract Classes


An abstract class has two uses Abstract classes facilitates reusability like any other base class
The data members and concrete methods of the abstract class can be reused

Abstract classes defined a standard interface for a family of classes


The concrete sub classes definitely will have the abstract methods implemented

Copyright 2007, Infosys Technologies Ltd

abstract Rules to follow


The following cannot be abstract
Constructors Static methods Private methods

Copyright 2007, Infosys Technologies Ltd

The final Keyword - done


The final modifier has a meaning based on its usage For member data and local data in methods
Primitives: read-only (constant) Objects: reference is read-only use all upper case letters by convention final int NORTH = 1;

The final methods cannot be overridden by the sub classes


public final void sample(){ //Method Definition }

Copyright 2007, Infosys Technologies Ltd

The final Keyword - done


A final classes cannot be extended
final class Test{ //Class Definition }

Copyright 2007, Infosys Technologies Ltd

Packages

Copyright 2007, Infosys Technologies Ltd

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

Copyright 2007, Infosys Technologies Ltd

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

package insurance; public class Policy{ //Code goes here }

Copyright 2007, Infosys Technologies Ltd

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

insurance.Policy policy = new insurance.Policy();

Copyright 2007, Infosys Technologies Ltd

Packages to Prevent Name Clash


Packages prevent the clash of class/interface names
More than one class/interface can have the same name They should be in two different packages The fully qualified names of these classes/interfaces will be different

Copyright 2007, Infosys Technologies Ltd

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

Importing all Classes and Interfaces


The statement import insurance.*
Imports all the classes and interfaces in the package insurance All the classes and interfaces in this package can be used without qualifying them with package name

BEST PRACTICE: Import only those classes that are required in your code, do not import the entire package

Copyright 2007, Infosys Technologies Ltd

Packages and classpath


Compiler and JVM must know location of the packages
An environment variable classpath needs to be set The classpath will be pointing to a folder be one level up the package folder If the folder hierarchy is C:\work\java\insurance, the classpath should be set using the following statement

>set classpath = %classpath%;C:\work\java

Copyright 2007, Infosys Technologies Ltd

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 }

A class Policy will be created in a package insurance.policy


Fully qualified name will be insurance.policy.Policy

Copyright 2007, Infosys Technologies Ltd

Access Modifiers - Revisited


Java has 4 access control modifiers
private: Accessible only within the class default: No keyword, Accessible only within the package protected: Similar to default with the addition that available to all child classes; that is, even if child class is in a different package public: Accessible to all

Data Members and Methods can have any of these specifier Classes and Interfaces can have either the public access or the default access

Copyright 2007, Infosys Technologies Ltd

Uses of Packages
Logical grouping of classes and interfaces Avoiding clash of names Provides an extra level of protection to its members

Copyright 2007, Infosys Technologies Ltd

Standard Java Packages


java.lang
Contains classes that form the basis of the design of the Java programming language No need to explicitly import this package The String class, System class etc, belong to this package

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

Copyright 2007, Infosys Technologies Ltd

Can you answer these questions?


What are packages? What are the uses of packages?

Copyright 2007, Infosys Technologies Ltd

Summary:
Method Overriding Dynamic Binding and Runtime Polymorphism Abstract classes The final keyword Interfaces Packages

Copyright 2007, Infosys Technologies Ltd

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.

Copyright 2007, Infosys Technologies Ltd

Você também pode gostar