Post on 20-Feb-2017
Introduction to Java andObject Oriented Programming
eLink Business Innovations - ©2000-2004
www.elinkbiz.com
Overview of WebSphere & EclipseReady, Set, Start Your IDEs!
eLink Business Innovations 2002-2004 ©
WebSphere & Eclipse
eLink Business Innovations 2002-2004 ©
Run a Wizard
Open a NewPerspective
List of OpenedPerspectives
Open Additional Views
Views
Editor Pane
Introduction to Object Oriented (OO) Concepts
eLink Business Innovations 2002-2004 ©
Programming Models
eLink Business Innovations 2002-2004 ©
Unstructured Programming
Main Program
Global DataUnstructured
programming. The mainprogram directly operates
on global data.
Procedural Programming
Main ProgramProcedural programming.
The main programcoordinates calls to
procedures and handsover appropriate data as
parameters.
Still uses global data attimes.
Procedure 1
Procedure 2
Procedure 3...
Execution Path
Modular Programming
Procedure 1
.
.
.
Module 1
Data (Global) + Data 1(Module 1)
Procedure 2 Procedure 1
.
.
.
Module 2
Data (Global) + Data 2(Module 2)
Procedure 2
Main Program
Data (Global)In Modular
programming, themain program
coordinates calls toprocedures in
separate modules(files) and passes
appropriate data asparameters.
Modular programs canstill have access to
global data.
Object OrientedProgramming Objects of the program
interact by sendingmessages to each other
and encapsulating data inthe object or passed as a
message.Object 1
Object 3
Object 2
Object 4
Evolution of Programming Models
Object Instantiation
eLink Business Innovations 2002-2004 ©
Program Execution
File Definition
In-Memory Instantiation
CreditCardImpl(creditcard1)
Instantiation
class abstract CreditCardImpl extends Account{ . . .}
CreditCardImpl(creditcard3)
CreditCardImpl(creditcard2)
CreditCardImpl creditcard1 = new CreditCardImpl();// Object Allocation
creditcard1.doSomething();
Denotes Sending Message to Object
Instantiation Properties:
Construction - Objects are created at execution time with new operator or declaration on some systemsDestruction - Objects are destroyed by delete operator, free call or garbage collectors
// Invoke Method
CreditCardImpl creditcard2 = new CreditCardImpl();CreditCardImpl creditcard3 = new CreditCardImpl();
Inheritance
eLink Business Innovations 2002-2004 ©
Account
Savings CheckingCreditCard
MoneyMarket
Visa AMEX
Interitance
"is-a"
"is-a"
Inheritance Properties:
Definition - Derivation from a Parent Cass to add/extend functionality in the childMultipliciy - Language dependent, inheritance can have single (one) or multiple (more than one parent) parent
Associations
eLink Business Innovations 2002-2004 ©
Associations Multiplicity
Customer Account1-*
Customer Account0 1
Customer Account1-* 1-*
"has-a or use"
Associations Properties:
Definition - Defines usage relationship with other objects.Multiplicity - Associations can 0 or more relationship of other objects.
Binary Associate
"has-a or use"
"has-a or use"
Participating Class
customer[]account[]
Role Name
Encapsulation
eLink Business Innovations 2002-2004 ©
Encapsulation
Account
Credit Card
"is-a"
public static int TYPE_CC = 1;
private String name = "";private int account = 0;
protected type = NONE;
public void setName( String name ){ this.name = name;}
CreditCard( int account ){ // Valid type = TYPE_CC;
// Invalid - Private this.account = account;}
Program Execution
// Allocate a new ObjectCreditCard card = new CreditCard("MyCard");
// Invalid - account is private// and not using access// method to data.card.account = 12345;
// Valid - Using access methodcard.setName("Changed My Mind");
Encapsulation Types:
private - Restricted access only to the Class, no external accessprotected - Restricted to the inheritance hierarchy or namespace (classes in the namespace)public - Visible to the world.
Polymorphism
eLink Business Innovations 2002-2004 ©
Polymorphism
Program Execution
// Allocate a new ObjectCreditCard card = new CreditCard("MyCard");
// Name Account - Casting Example((Account)card).getName();
// Name from Credit Card// Defaultcard.getName();
// Virtual methodcard.getDescription();
Account
Credit Card
"is-a"
// Abstract Methodpublic abstract void getSummary(){ return("Not summary for Account");}
// Pure Virtual Method - No Bodypublic abstract void getDescription();
// Overloaded Method from Accountpublic String getSummary(){ return("Summary for Credit Card");}
// Required Implemented Method from Accountpublic String getDescription(){ return("Credit Card Description");}
Polymorphism Properties:
Virtual - Replace or extend by overloading/overiding the functionality of a parent's class methodPure Virtual - Parent requires children to implement a specific method. Parent provides no implementation.
Construction/Destruction
eLink Business Innovations 2002-2004 ©
Construction & Destruction
Account
Credit Card
"is-a"
Program Execution
// Construction// Allocate a new ObjectCreditCard card = new CreditCard("MyCard");
// Java object destructioncard = null; // GC will process
// Destruction (Concept - C++)// NOT available in Javadelete card;
CreditCard()
Account()
Instantiation Order Destruction Order
~Account()
~CreditCard()
Constructor Behavior:
Default - Default constructor provided if not explicitly specified in class.Execution - Constructors are called only once for the creation of an objectReturn Types - Constructors DO NOT support return types. To report errors they throw Exceptions.Overloading - Constructors can be overloaded using various parameter types.
Destructor Behavior:
Default - Default constructor is provided if not explicity specified on systems that support destructorsExecution - Destructors are called only once at destruction of an objectReturn Types - Destructors do NOT support return types. To report errors they throw exceptions.Overloading - Destructors can NOT be overloaded with multiple parameter types.
Interface
eLink Business Innovations 2002-2004 ©
Interfaces
Program Execution
// Allocate a new Customer ObjectCustomerAccount custAccount = new AccountImpl();
// Access Customer RolecustAccount.getBalance();
// Allocate a new Teller ObjectTellerAccount tellerAccount = new TellerAccountImpl();
// Access Teller's RoletellerAccount.getAuditRecords();
AccountImpl(Class)
CustomerAccount(Interface)
// Interface Definitionpublic int getBalance();
Interface Properties:
No Code - Interfaces contain no code, just the interface definitions.No Statics - Interfaces cannot contain static interface definitions, because of the dependencies on classes for static initialization, excep static final for constants definitions.Multiplicity - Classes can implement multiple interfaces
TellerAccount(Interface)
Dependency
class AccountImpl implements CustomerAccount, TellerAccount...// Implementationpublic int getBalance(){ return( balance );}// Implementationpublic AuditRecord[] getAuditRecords(){ return( records );}
// Interface Definitionpublic int getAuditRecords();
Templates
eLink Business Innovations 2002-2004 ©
Templates
Customer(Source)
Template Properties:
Types - Templates allow strong typing of codeCookie Cutter - Allows creation of source that can be reused again and again (cookie cutter)Drawbacks - Causes considerable code growth in size, some compilers type to optimize this feature, but it's a macro type feature.Examples - C++ Standard Collections, Microsoft Foundation Classes, Corba IDL languages
Customer(New Source)
Account(Source)
Account(New Source)
Generated
Generated
Template Definition
template <typename T>class List{ private T list[];
public List<T []> list() { return(list); }}
Program Execution
// Account Using TemplateAccount account = new Account();Account alist[] = null;
list = account.list();
// Customer Using TemplateCustomer customer = new Customer();Customer clist[] = null;
list = customer.list();
Dependency (Utilizes)
Dependency (Utilizes)
Execution Path
Namespace
eLink Business Innovations 2002-2004 ©
Namespaces
Namespace Properties:
Resolution - Allows multiple names to exist in the same namespace with no conflicts.
Company 1(no namespace)
Account
Company 2(no namespace)
Account
Problem (Resolving)
Company 1namespace: com.company1.accounting
Account
Solution (No Conflicts)
Company21namespace: com.company2.accounting
Account
Naming Conflict
Exceptions
eLink Business Innovations 2002-2004 ©
Exceptions
Exception Properties:
Usage - Should not be used for normal flow control (like return codes). Exceptions require additional system overhead on most systems.Extentions - User can inherit from exceptions to create their own exception classes.
Program Execution
try{ // Allocate a new Object CreditCard card = new CreditCard(0);}catch( NoAccountException nae ){ // Process Exception // Log something}catch( Exception unknown ){ // Report Unknown Exception}finally{ // Always do something}
Credit Card
// ConstructorCreditCard( int account ) throws NoAccountException{ if( account == 0 ) throw NoAccountException();}
Always called with/without Exception
UML Diagram
eLink Business Innovations 2002-2004 ©
Introduction to the Java Model & History
eLink Business Innovations 2002-2004 ©
Java Objects
eLink Business Innovations 2002-2004 ©
java.lang
Java Object Hiarchy
Object
String Char Others
java.awt
Graphic
Implied Inheritance by Language
Security
eLink Business Innovations 2002-2004 ©
Java Security
Web Application
User
----------------------------------------
01010110101010010101010101
Web Service
01010110101010010101010101
Mobile Clients
Service Layer Legacy Systems
MQ
CICS
DB2
LDAP
1
1
1
2
2
2
3
3
3
2
2
2
4
5
2
2
2
2
Security Points:
1. Authentication - User,Device or Service is Authenticated to the system or service (JAAS)2. Transmission - Communications data is transmitted in Secure Socket (SSL or TLS) (JSSE)3. Authorization - User, Device or Services is Authorized to use services, roles, (e.g. read/write/etc) (JAAS)4. Isolation - Protectecting bad users or applications from each other. Sandbox issolation.5. Validation - System validation between systems using6. Auditing & Credentials - Auditing of activites for non-repudiation purposes along with credential monitoring7. Encryption - Protecting data stored in persistence layer by encryption, hashing or certificates
4
4
7
1
3
7
5
5
5
5
5
6
3
3
3
Threads & Locks
eLink Business Innovations 2002-2004 ©
Java Threading & Locking
Thread Properties:
Create/Destroy - Ability to create and destroy threads in applicationSuspend/Resume - Ability to suspend an resume threadsPriority - Ability to set the execution priority of threadsSynchronization/Locking - Create synchronized blocks of code that serialize data access between threadsEvents/Semaphores/IPC - Supports wait and notify on objects to synchronize activities between threads
Main Program(main thread)
Test 1 Thread
Test 2 Thread
Data
Begin Process
End Process
Thread Loops
Do workasynchronously
Do workasynchronously
Thread Ends
Thread Ends
Lock Data
Unlock Data} Synchronization Block
Wait
Start Thread
Start Thread
Notify Thread
Threads are known by name.
Memory Management
eLink Business Innovations 2002-2004 ©
Java Program
Java Memory Management
Memory Management Properties:
Allocation - New allocation of objects is requested by the program and managed by the VMDeAllocaiton - Object destruction and collection is managed by the Garbage CollectorDistributive GC - If working with distributive objects they are collected remotly then passed off the local GCHints - It's always good to assign null to objects or clear collections when finished using them
Java Virtual Machine
Garbage Collector (GC)
Object
Request New Object (new)
Object
Memory Manager
NewObject
Returned
Destroy Object
Object = null
Garbage Collector Checks & Collects Unreference
Objects
Inform MemoryManager Object has
been Collected
Internationalization
eLink Business Innovations 2002-2004 ©
Java Internationalization
Internationalization Properties:
Unicode - All Strings and Chars (2 bytes not 1) in Java are in Unicode Representation and UTF8 for ASCIILocale - Users international location. Includes country code and regional informationResources - Property names are used to fetch resource bundle based on User Locale
User - English
User - Spanish
User - Chineese
Application
----------------------------------------
EnglishResource Bundle
SpanishResource Bundle
ChineeseResource Bundle
Check User Locale
get msg.hello
returns "Hello"
get msg.hello
returns "Hola"
get msg.hello
returns "\03\0d\02\0e\0f" //Unicode String Representation
Serialization
eLink Business Innovations 2002-2004 ©
Java Serialization
Serialization Properties:
Marshaling / Un-Marshaling - Enables "flattening" of objects in Java with minimal code changesCaution - Be careful the "deepness" of an object and it's dependencies (inheritance & associations)Externalization - Enables custom marshaling code like, encryption, compression, base64, etc.
Stored/Retrieved to/from a Database
Object
Serialize
010101010101010101010101010
De-serialize
Object
Sent Across a Network
Object 010101010101010101010101010 Object
Sent Across a Network
UseCustom
Encoding
UseCustom
Decoding
Externalization
JDK Packages
eLink Business Innovations 2002-2004 ©
Collections
eLink Business Innovations 2002-2004 ©
Java Collections
Collection Properties:
Framework - Common framework to standardize management of objects without writing custom codeCaution - Remember to clear collections or set colleciton object to null so memory leaks don't appearSynchronization - Not all collections support synchronization for threading, check the documentation on collection.
Vector
Object
Object
Object
Hashtable
Object
Object
Object
MyKey_1 =
MyKey_2 =
MyKey_3 =
Collections Classes
- AbstractCollection - AbstractList- AbstractSet- ArrayList,- BeanContextServicesSupport- BeanContextSupport,- HashSet- LinkedHashSet- LinkedList- TreeSet- Vector
IO Streams
eLink Business Innovations 2002-2004 ©
Java Streams
Stream Properties:
Framework - Common framework to standardize input/output management of data without writing custom code
Object
Input Stream Classes
- AudioInputStream- ByteArrayInputStream- FileInputStream- FilterInputStream- InputStream- ObjectInputStream- PipedInputStream- SequenceInputStream- StringBufferInputStream- AbstractCollection
Ouput Stream Classes
- ByteArrayOutputStream- FileOutputStream- FilterOutputStream- ObjectOutputStream- OutputStream- PipedOutputStream
-----------
File
Socket
Stream Reader/Writer
Stream Collection
InputStream
OutputStream
Networking
eLink Business Innovations 2002-2004 ©
Java Networking
Network Properties:
Framework - Common framework to standardize networking without writing custom code
Network Classes (Some)
UDP Layer
- DatagramSocket- DatagramPackets- MulticastSockets- DatagramChannel (NIO)
TCP Layer
- Socket- SSLSocket- SocketChannel (NIO)- InetSocketAddress (NIO)
Application Layer
- URLConnection- HTTPURLConnection- JarURLConnection- ServerSocket- SSLServerSocket- RMIClientSocketFactory/Listener
IP
UDP Layer (Datagrams)
TCP Layer
Application Protocols
TCP/IP Network Stack
Graphical Interfaces (GUI)
eLink Business Innovations 2002-2004 ©
2D Graphics
eLink Business Innovations 2002-2004 ©
Introduction to the Java Language(Syntax & Structure)
eLink Business Innovations 2002-2004 ©
Comments & JavaDocs
eLink Business Innovations 2002-2004 ©
Single Line Comment // This is a Java Single Line Comment Comment Block
/* * This is a mult-line block comment * Second line, so on. */ JavaDoc Comments to Generated Docs /** * @author Bubba Gump * @example <h1>test message</h2> * * @todo */
JavaDoc Example
eLink Business Innovations 2002-2004 ©
Identifiers
eLink Business Innovations 2002-2004 ©
/** * Example of Java Coding Syntax * */class CustomerAccount // First letter of each phrase, including first{ private String accountNumber = null; // Field name lower case start, then uppercase // for each phrase /** * Return an account number * @return accountName */ public String getAccountNumber() // First letter lowercase, getter matches Field { // in Uppercase of each Phrase return( accountNumber ); } /** * Set the account number * @return accountName */ public void setAccountNumber( String accountNumber ) // Setter structure same as getter { this.accountNumber = accountNumber; }}
Literals
eLink Business Innovations 2002-2004 ©
long count = 10; // 10 is the literal valuechar name = ’A’; // ‘A’ is a Unicode literal characterString name = “test”; // “Test” is a Unicode literal String
Java Logic Flow
eLink Business Innovations 2002-2004 ©
Java Development Process
Account.java
class Account{ public static void main( String args[]) { System.out.println("Hello World"); }}
Java Compiler
010101010101010010101010101010101010101010101010101010101010100101
Account.class
Java Interpreter Java Interpreter Java Interpreter
Windows Linux iSeries
Names Need to Match
Generated Byte-codes
HelloWorld
HelloWorld
HelloWorld
Java Interface
eLink Business Innovations 2002-2004 ©
Interface Decomposition (File Representation)
interface CreditCard extends Account{ public static final TYPE_NONE = 0;
public setName(char name); public setNumber(char number); public setType(int type);}
Interface Definition (Noun)
} Method Definitions (Verb)
Visibility (Public ONLY)
Parent Inherited Interface
Constant Definitions
Java Class
eLink Business Innovations 2002-2004 ©
Class Decomposition (File Representation)
class abstract CreditCardImpl extends AccountImpl implements CreditCard{
private char name = 0; private char number = 0; private static int amount = 0;
Account(){}; public void finalize(){};
static { amount = 100; }
public setName(char name) { this.name = name; }
public void validate() throws ValidationException { }
public abstract setNumber(char number) { this.number = number; }
public abstract setType(int type);}
} Data Declaration
Constructor
} Method Body
Internal Object Reference(reserved word)
Visibility (Encapsulation)
Parent Inherited Base Class
} Virtual Method
Pure Virtual Method
Interface Definition
Static Initializer
Exception Declaration
Destructor Like
Class Definition (Noun)
Method Declaration (Verb)
Packages (Namespaces)
eLink Business Innovations 2002-2004 ©
Java Packages
Package Properties:
Naming - Package naming convention reads from left to right. Usually the internet domain name, then user defined componentsDefault Package - One packages is imported into the class by default. That is javax.lang.* .This package doesn't have to be imported explicitly like other packages.Folders - The package name location has to match the directory structure on the file system so java compiler can find the package.
Object
Account
Savings
Customer
import java.net.*;import java.io.ByteArrayInputStream;
ByteArrayInputStream stream = new ByteArrayInputStream();
Importing Packages
Declaring Packages
com.unitedbank.atm.Customer
package com.unitedbank.atm;
class Customer{....}
----------------------------------------maps to a file system directory
com/unitedbank/atm/Customer.java
Java Objects
eLink Business Innovations 2002-2004 ©
Java Objects
Casting Properties:
Allocate - Reserved work "new" to create an instanceDe-Allocate - Set object to reserved word "null". Tells the garbage collector object is ready to be collected.
Object
Account
Savings
Customer
// Default InitializationAccount account = null;
// Instantiate new account objectaccount = new Account();
// Free object - hint to GCaccount = null;
Java Casting
eLink Business Innovations 2002-2004 ©
Java Casting
Casting Properties:
Strong Types - Collection values are commonly cast in JDK 1.0-1.4, however in JDK 1.5 introduces strong types to the Java language. Template like feature.
Object
Account
Savings
Customer
Customer customer = new Customer();Savings savings = new Savings()Account account = null;
// Cast Example 1account = (Account)savings; // Good Cast
// Cast Example 2Vector list = new Vector();list.add( savings );
account = (Account)list.get(0); // Good Case
// Case Example3 - Bad Cast// causes a ClassCastExceptionaccount = (Account)customer;
Java Exceptions
eLink Business Innovations 2002-2004 ©
Java Exceptions
Exception Properties:
Usage - Exceptions should be used in exceptional conditions but not as flow control flow for an application.
Catching an Exception
try{ // Do work that throws the exception}catch( java.lang.NullPointerException npe ){ // Catch the concrete exception type, // you should not catch a generic Exception}finally{ // Optional - good for cleanup code // like database connections, etc}
Custom Exceptions (Extending)
class MyNewException extends Exception{ public String getReason() { return( "code is broken" ); }}
Throwing Exceptions
class MyClass{ public String checkData(String data) throws NullPointerException { if( data == null ) throw new NullPointerException(); }}
Java Threads
eLink Business Innovations 2002-2004 ©
Java Threads
Exception Properties:
Usage - Provide multi-tasking support for java and are easy to implement and useStarvation - A thread that abuses system resource and causes other threads to starve for time to run. Usually a bad loop.Deadlock - Circular dependencies between two threads both end up waiting on each other to complete.Race Condition - Two threads that go after the same resource that are not synchronized. It's random who receives the resource first.
Creating a Thread
// Create a new Thread InstanceThread myThread = new Thread("Worker Thread", new MyThread() );
// Start the threadmyThread.start();
// Dispatch thread to wake upmyThread.doSomething();
Declaring a Thread
class MyThread implements Runnable{ private static boolean terminate = false; private static Object lock = new Object();
public void doSomething() { synchronized(lock) { lock.notify(); } }
// Entry point for the thread public void run() { while(!terminate) { synchronized(lock) { lock.wait(); } } }}
First Java Program!
eLink Business Innovations 2002-2004 ©
Perspective
eLink Business Innovations 2002-2004 ©
Projects
eLink Business Innovations 2002-2004 ©
Project Workspace
eLink Business Innovations 2002-2004 ©
Packages
eLink Business Innovations 2002-2004 ©
Classes
eLink Business Innovations 2002-2004 ©
Attributes
eLink Business Innovations 2002-2004 ©
Running Our Program
eLink Business Innovations 2002-2004 ©
Debugging
eLink Business Innovations 2002-2004 ©
Testing
eLink Business Innovations 2002-2004 ©
package com.unitedbank.atm.test; import com.unitedbank.atm.service.ServiceImpl;import com.unitedbank.atm.service.CustomerService; import junit.framework.TestCase; /** * */public class TestCustomerService extends TestCase{ public void testGetCustomerAccounts() {
CustomerService service = new ServiceImpl(); // fetch from repositoryservice.getAccounts("bob", "password");
}}
Test - Executing
eLink Business Innovations 2002-2004 ©
Questions ?
eLink Business Innovations 2002-2004 ©