You are on page 1of 77

My Team

• Dr. Atif Aftab Ahmed Jilani


– Email: atif.jilani@nu.edu.pk
– Office: Room (114-F, 1st Floor Computer Science Block)
– Office Ext: 325
• Ms. Sidra Khalid
– Email: sidra.khalid@nu.edu.pk

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

• Start with Q & A


• Main Lecture
– No short breaks in the middle
Outside of Class
• Download code and lecture materials from the Slate course folder

• Walk through examples and browse Javasoft documentation (2 to 3


hours)

• Do homework (considerable number of hours)


Feel welcome
• …with stupid questions
– just ask yourself the same question first
• …to help your peers with new bright ideas.
– (never share syntax though)
• …to have fun and explore
Cheating vs. Helping
• Read the “Code of honor”.
• Talk with your peers
– Share ideas, not code/syntax.
– Mention it in the report.

• Don’t get stuck for too long


– This is a high pace course
– Don’t sit at home. Get up early and join your peers on campus

• 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 zero balance */


public BankAccount() {
this(0);
}

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

Person accountHolder = new Person(“Ahmed”);


studentFund.setAccountHolder(accountHolder);

} What changes to be made in BankAccount class for


this association?
}
Reference vs. Values
• A java object is a memory structure
• An object reference holds the memory address of an object

BankAccount collegeFund =

BankAccount studentFund =
Each BankAccount
collegeFund = new BankAccount(1000); object has its own
balance,
accountNumber
collegeFund = BankAccount
balance = 1000.0

accountNumbe = 1

studentFund = new BankAccount(500);

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

num1 num2 num1 num2

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.

protected void finalize() throws IOException {


if (fd != null) close();
}
Types of variables and methods in a
Java class
• There are two main types of variables/fields:
– instance variables
– class (or static) variables
– Instance variables store information pertaining to one particular
object's state
– Class variables store information pertaining to all objects of one
class
• Likewise, there are two types of methods:
– Instance methods
– Class (static) methods
– Instance methods belong to individual objects; whereas class
methods belongs to the whole class.
– Note: In class method, you cannot use this and instance
variables.(why?)
Class/Instance Method or Variable
• Class/static method or variable is associated with a class
rather than instance
• Call with class name instead of object
class BankAccount {
public static void main(String[] args) {
System.out.println(Numeric.approxEqual(a,
b));
}
}
• Non-static methods or variables are known as instance
methods or instance variables
• To refer to instance variables or methods, you must
reference the variables from an object.
• Too many static methods are a sign of too little Object-
oriented
Class/Instance Method or Variable

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

• object1 == object2 means `do object1 and object2


have the same address in memory?’
• object1.equals(object2) means are they equal, for
example do they have the same values of all fields?

• For two Strings string1 and string2,


string1.equals(string2) means, do they have the
same characters in the same sequence?
• string1 == string2 means `are string1 and string2
stored at the same address in memory?’
Subclass Example
public class GraphicCircle extends Circle
{ // Extra fields
Color outline, fill;
// Extra constructors
public GraphicCircle(Color edge, Color fill)
{ x = 0.0; y = 0.0; r = 1.0;
outline = edge; this.fill = fill; }
public GraphicCircle(double r, Color edge, Color fill)
{ super(r); outline = edge; this.fill = fill; }
// Extra methods
public void draw(Graphics g)
{ 1g.setColor(outline); g.drawOval(x-r, y-r, 2*r, 2*r);
g.setColor(fill); g.fillOval(x-r, y-r, 2*r, 2*r); }
}
Abstract Classes
• Abstract class allows us to declare methods without
implementation.
– the unimplemented method is called an abstract method.
– Subclasses can extend abstract class and provide implementation
of all or portion of abstract methods.
• benefit of an abstract class
– methods may be declared such that the programmer knows the
interface definition of an object,
– however, methods can be implemented differently in different
subclasses of the abstract class.
• Cannot instantiate an object of an abstract class, but variables
of the type can be used to hold references of concrete sub-class
objects
Abstract Classes (cont.): an example
public abstract class Shape
{ public abstract double area(); // abstract methods
// to be implemented by subclasses
public abstract double circumference();
}

public class Circle extends Shape


{ protected double r;
protected static final double PI=3.141592653;
public double Circle() { r = 1.0; }
public double Circle(double r) { this.r = r; }

// implementation of two abstract methods of shape class


public double area(){ return PI*r*r; }
public double circumference() { return 2*PI*r; }

public double getRadius() { return r; }


}
Visibility modifiers
The visibility modifiers determine which class members can be
referenced from where and which cannot.
• public members:
– all classes
• protected members
– all classes in the same package +
– all subclasses (and subsubclasses …)
– Note: Java has no notions of public, private or protected inheritance
as in C++; all inheritances are public.
• package members [default visibility]
– all classes in the same package
• private members
– can only be used in the same class where the member is defined.
The ‘this’ and ‘super’ keywords
• The this keyword can be used to refer to the current object
of the class.
• The super reference can be used to refer to the parent
class, and is often used to invoke the parent's constructor
or access parent attributes
Interface Summary
• An interface defines a protocol of communication
between two objects.
• A Java interface is a collection of abstract methods and
constants
• An abstract method is a method header without a
method body (i.e., no implementation)
• An abstract method in an interface can be declared
using the modifier abstract, but because all methods in
an interface are abstract, it is usually left off.
– cf: abstract methods in an abstract class must be declared
explicitly using the abstract modifier.
• An interface is used to formally define a set of methods
that a class will implement
Interfaces

interface is a reserved word


None of the methods in an
public interface Doable interface are given
{ a definition (body)
public void doThis();
public int doThat();
public void doThis2 (float value, char ch);
public boolean doTheOther (int num);
}

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

• A class formally implements an interface by


– stating so in the class header
– providing implementations for each abstract method in the interface

• If a class asserts that it implements an interface, it must define all


methods in the interface or the compiler will produce errors.
An Interface example
interface Printable {
public String name();
public String print();
} // interface Printable

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

class ImageFile extends BinaryFile implements Printable {


public ImageFile (String id, int size, byte[] data) {
super(id, size, data);
} // constructor ImageFile
public String print() { return new String (data); }
} // class Image_File
Using Interfaces
public class PolymorphicPrinter {
public static void main (String[] args) {
byte[] logoData = {41, 42, 49, 44 };
TextFile report = new TextFile
(“Reprot 1", 1024, "One two three …");
ImageFile logo = new ImageFile(“Picture 1", 4, logoData);
PrintLogger daily = new PrintLogger();
daily.log (report);
daily.log (logo);
}
}
Polymorphism via Interfaces
public class Printer {
public static void main (String[] args) {
byte[] logoData = {41, 42, 49, 44 };
Printable printables[] = new Printable[2];
printables[0] = new TextFile
(“Reprot 1", 1024, "One two three …");
printables[1] = new ImageFile(“Picture 1", 4, logoData);
PrintLogger printer = new PrintLogger();

for (int i=0; i< printables.length; i++){


printer.log(printables[i];
}
}
}
Java Basics
Placing classes in Package
• To placing classes in package, start file with
package packagename;

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

Account Bond Trust

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 {

public void deductTax(TaxTotaller tt,


float taxRate, Account a) {
float tax = 0.0f;
tax = (a.getBalance() * taxRate);
a.setBalance(a.getBalance() * (1 - taxRate));
tt.addTax(tax);
}
public void deductTax(TaxTotaller tt,
float taxRate, Trust t) {
float tax = 0.0f;
tax = (t.getBalance() * taxRate);
t.setBalance(t.getBalance() * (1 - taxRate));
tt.addTax(tax);
}

public void deductTax (TaxTotaller tt,


float taxRate, Bond b){
float tax = 0.0f;
tax = (i.getBalance() * taxRate);
b.setBalance(b.getBalance() * (1 - taxRate));
tt.addTax(tax);
}
}// end of TaxHandler
Solution: Association
class ChequeAccount extends Account {
private float overdraftLimit = 0.0F;

public ChequeAccount(float initialBalance,


float initialLimit){
...
}
public boolean withdraw(float amount) {
...
}
// This method forwards the message to deduct tax
// to a TaxHandler object:
public void deductTax(TaxTotaller t,
float taxRate) {
TaxHandler th = new TaxHandler();
th.deductTax(t, taxRate, this);
}
}
Problem?
Stored in vector as object type

Vector acct 1 trust1 acct2 Object n

Cheque Institution Cheque Bank


Account Trust Account Trust

The real types of objects


One Solution: RTTI
Object o = null;
Enumeration e = v.elements();
while (e.hasMoreElements()) {
o = e.nextElement();
if (ChequeAccount.class.isInstance(o)) {
((ChequeAccount)o).deductTax(t, 0.5);
} else if (BankBond.class.isInstance(o)) {
((BankBond)o).deductTax (t, 0.5);
} else {
((InstitutionalTrust)o).deductTax(t, 0.5);
}
}

• 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){
...
}
. . .
}

class BankBond extends Account implements Taxable {


. . .
public void deductTax(TaxTotaller t, float taxRate){
...
}
. . .
}
Remaining Problem
• To remove the overloaded methods in TaxHandler we need to
extend the interface:

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

You might also like