Professional Documents
Culture Documents
Office Hours:
Will later be Displayed outside my office.
• TA
– Mian Muhammad Usman
– Muhammad Usman Kaisser
• Classes
– 1+1 hrs. Weekly ( Adjust your clashes Accordingly)
• Lab
– 1 Lab per week ( 3 Hours)
Overview of Course
• Goal is to give students a roadmap and make it easier for them to
learn the details on their own
– If you work hard, you will know the basics of a lot of different
technologies and libraries
– You will understand when they are used and the relative strengths and
weaknesses
• The course will help to utilize the incredible power of component
oriented, Network Centric and distributed computing of Java SE and
Java EE to create effective, scalable, maintainable, and adaptable
applications to solve an extremely wide range of problems.
Target Students
• Undergraduate computer science students interested to pursue a
software development career
• The course is designed for students of 5th semester
Lecture Format
• Discussions are important
• This is not a pure lecture-based course
– There are in-class labs
– A parallel mandatory lab session
• Don’t cheat
– There are two kinds of people. Those who listen, and those who should
listen.
JAVA Programming
Why Java Programming ?
What is Java?
• A widely used and effective OOP language
• Over 10 million developers and 15 billion devices run Java
worldwide!
• Run-time Environment (tools, class library, documentation)
• Compiled for speed
• Interpreted
• Portable (architectural-neutral via JVM)
• Directly supported by major OS’s
– Apple, Linux, Windows, Sun, etc
Compilation vs Interpretation
Write Once Run Anywhere
What Can Java Do?
• Three types of Java Programs
– Applets
• run within a Java-enabled browser
– Standalone Applications
• a standalone program that runs directly on the Java
platform, examples
– Server Applications
• Servlets
• JSP, JSF, Struts
– Mobile Application
• Android
Object Oriented Benefits
• Better software design
– different way of thinking about software
– software can more closely models real world problem being
addressed
– domain experts can more easily participate in initial software design
• Easier to maintain
– changes are more localized
• Easier to extend
– easy to make extensions to existing functionality
• Less code to write
Features Important to Developer
• Object-Oriented (benefits discussed earlier)
• Productive
– fewer compiles are needed than with C/C++
– faster development cycle since linking is not required
• Familiar
– syntax resembles C and C++
• Garbage collection
– avoids memory leaks (failing to free memory that will no longer be
used)
– avoids accessing freed memory
• Extensible
Aspects of C/C++ Improved in Java
• Time consuming links
• Confusing features
– multiple inheritance, operator overloading, templates
• Dangerous features
– unsafe casts between unrelated types(Now controlled through
generics)
– array access w/o bounds checking
– lack of memory management (garbage collection)
• Non-OO features
Reasons to Select Java
• Web-based applications
– common interface to applications/data inside and outside company
• Portability
– even for non-web-based applications
– applications will run on all major platforms
• Distributed Applications
– RMI is easier and less expensive than CORBA but lacks services
• Networking
– supports TCP and UDP sockets
– can access remote data using a variety of protocols
Reasons to Select Java (Contd.)
• Multithreading
– can utilize multiple processors
– more natural style of coding for some applications
• Object-oriented
– encourages better software design
– easier to maintain, extend and reuse
• Garbage collection
– software is less prone to errors
• Productivity
– fewer source files need to be compiled when changes are made
– eliminates time to repeatedly link executables during development
Java IDE Tools
• Eclipse
• NetBeans
• Enide Studio
• Blue J
• JDeveloper
• And so on…
Tentative Marks Distribution
10
Assignments %
Project 10 %
Quiz 5 %
15
Labs %
Mid Term 20
Exam %
40
Final %
100
Total %
Object Oriented Development
Selecting Classes
• A class represents a single concept
• Which classes to select depends on the domain of the application
being developed
– Concepts from real life
• BankAccount
• Student
• Purse
– Concepts from mathematics:
• Point
• Rectangle
• Ellipse
– Action classes
• StringTokenizer
• Random (better called RandomNumberGenerator)
– Utility classes--no objects, only static methods
• Math
Example – BankAccount.java
/**
* A bank account has a balance that can be changed
* by deposits and withdrawals.
*/
public class BankAccount {
private static int lastAccountNumber;
private int accountNumber;
private double balance;
/**
* Constructs a bank account with a given balance
* @param initialBalance the initial balance
*/
public BankAccount(double initialBalance){
balance = initialBalance;
lastAccountNumber++;
accountNumber = lastAccountNumbre;
}
BankAccount.java
/** Deposits money into the bank account.
* @param amount the amount to deposit
*/
public void deposit(double amount) {
double newBalance = balance + amount;
balance = newBalance;
}
/**
* Withdraws money from the bank account.
* @param amount the amount to withdraw
*/
public void withdraw(double amount){
double newBalance = balance - amount;
balance = newBalance;
}
/**
* Gets the current balance of the bank account.
* @return the current balance
*/
public double getBalance() { return balance; }
}
BankAccount Driver
public class Driver{
public static void main(String args[]){
BankAccount collegeFund;
BankAccount studentFund;
collegeFund = new BankAccount(1000);
studentFund = new BankAccount();
}
BankAccount Driver - Association
public class Driver{
public static void main(String args[]){
BankAccount collegeFund;
BankAccount studentFund;
collegeFund = new BankAccount(1000);
studentFund = new BankAccount();
BankAccount collegeFund =
BankAccount studentFund =
Each BankAccount
collegeFund = new BankAccount(1000); object has its own
balance,
accountNumber
collegeFund = BankAccount
balance = 1000.0
accountNumbe = 1
studentFund = BankAccount
balance = 500.00
accountNumbe =
2
Value Assignment - Primitives
• For primitive types, the act of assignment takes a copy of a
value and stores it in a variable
int num1 = 5, num2 = 12;
num2 = num1;
Before After
5 12 5 5
Assignment - Objects
• For object references, assignment copies the memory location:
studentFund = collegeFund;
Before After
studentFund collegeFund studentFund collegeFund
Aliases
• Two or more references that refer to the same object are called
aliases of each other
• One object (and its data) can be accessed using different
variables
• Aliases can be useful, but should be managed carefully
• Changing the object’s state (its variables) through one reference
changes it for all of its aliases
• Ex:
Circle c = new Circle(1.0, 2.0, 3.0);
Circle d = c; // c and d are aliases.
c.r = 4.0; // d.r == 4.0 now.
Destroying Objects
• When an object no longer has any valid references to it, it
can no longer be accessed by the program
– It is useless, and therefore called garbage
– Java performs automatic garbage collection periodically, returning
an garbage object's memory to the system for future use
– Hence it is needless to explicitly destroy objects.
• How can references to objects '' go away'‘ ?
– Re-assigning object variables (a = b; a = null) or
– object variables (locals or parameters) going out of scope.
• no more malloc/free bugs
Object Finalization
• A constructor method performs initialization for an object; a Java
finalizer method performs finalization for an object.
• Garbage collection only help freeing up memory.
• But there are other resources needed to be released.
– file descriptors, sockets, lock, database connection.
Each BankAccount
object has its own
balance,
accountNumber
collegeFund = BankAccount
balance = 1000.0
accountNumbe = 1
stationaryFund = BankAccount
balance = 5000.0
accountNumbe = 2
studentFund = BankAccount
There is single
lastAccountNumber
balance = 5000.0 field for the
BankAccount
accountNumbe = 3 class
BankAccount.lastAccountNumber = 2
Object/Reference Types: Consequences
A semicolon immediately
follows each method header
Examples: Enumeration
• Enumeration interface just used in Vectors and Hashtables.
This has declaration as follows:
public interface Enumeration {
boolean hasMoreElements();
Object nextElement();
}
• Objects which implements them will belong to some other
class
Examples: Iterators
• Iterator takes the place of Enumeration in the Java collections
framework
• Differ from enumerations in two ways:
- Allow the caller to remove elements from the underlying
collection during the iteration with well-defined semantics
- Method names have been improved
package java.util;
public interface Iterator {
boolean hasNext();
Object next();
void remove();
}
Interfaces
• An interface cannot be instantiated
– Doable d = new Doable(); // error
• Like a class, an interface can be used as the type of variables.
– Doable a, b;
• Methods in an interface have public visibility by default
class PrintLogger {
public void log (Printable file) {
System.out.println (file.name() + " : " + file.print());
} // method log
} // class PrintLogger
class File {
protected String id; protected int size;
public File (String id, int size) {
this.id = id; this.size = size;
} // constructor File
public String name() { return id; } // method name
} // class File
class TextFile extends File implements Printable {
protected String text;
public TextFile (String id, int size, String contents) {
super(id, size); text = contents;
} // constructor TextFile
public String print() { return text; }
} // class TextFile
An Interface example
class BinaryFile extends File {
protected byte[] data;
public BinaryFile (String id, int size, byte[] data) {
super(id, size); this.data = data;
} // constructor BinaryFile
} // class BinaryFile
package org.nuces.courses;
public class AdvanceProgramming{
...
}
• Default package has no name, no package statement
Importing Packages
• Can always use class without importing
java.awt.Color backgroundColor = new java.awt.Color(…);
• Tedious to use fully qualified name
• Import lets you use shorter class name
import java.awt.Color;
. . .
Color backgroundColor = new Color(. . .);
• Can import all classes in a package
import java.awt.*;
• Never need to import java.lang
Package Names
• Package names should be unambiguous
• Recommendation: start with reversed domain name
org.omg.CORBA
org.nuces.advprogramming
• Path name should match package name
com/nuces/advprogramming/Course.java
• Path name starts with class path
export CLASSPATH=/home/iffee:.
Base directories and subdirectories for packages
Object Oriented Paradigm: Features
Encapsulation
Data Abstraction
Single Inheritance
Polymorphism
OOP
Paradigm
Persistence
Delegation
Multiple Inheritance
Java’s OO Features
Encapsulation
Data Abstraction
Single Inheritance
Polymorphism
OOP Java
Paradigm
Persistence
Delegation
Multiple Inheritance
Inheritance, Interfaces and
Association
• Three ways to get functionality in an object:
– Implement it directly
– By association
– By Inheritance
A Problem
Insti
Saving Cheque Govt Bank Private
tution
Account Account Bond Bond Trust
Trust
Taxable
Solution: Implement Direct
• Implement a method deductTax in each class
public void deductTax (TaxTotaller t, float
taxRate) {
float tax = 0.0f;
tax = getBalance() * taxRate);
setBalance(getBalance() * (1 - taxRate));
t.addTax(tax);
}
• Problems?
Solution: Association
public class TaxHandler {
• Problem?
Another Solution
• Create a new inheritance hierarchy from which all taxable
classes inherit and cast them to this
• Use an interface
interface Taxable {
void deductTax(TaxTotaller t, float taxRate);
}
• Each object can now be cast to the type Taxable without the
nested if statements.
Another Solution Contd.
class ChequeAccount extends Account implements Taxable {
. . .
public void deductTax(TaxTotaller t, float taxRate){
...
}
. . .
}
interface Taxable {
float getBalance();
boolean setBalance(float balance);
void deductTax(TaxTotaller t, float taxRate);
}
Remaining Problem: Contd.
class TaxHandler {
public void deductTax(TaxTotaller tt,
float taxRate, Taxable t) {
float tax = 0.0f;
tax = (t.getBalance() * taxRate);
t.setBalance(t.getBalance() * (1 - taxRate));
tt.addTax(tax);
}
}
Thanks