Download objects

Document related concepts
no text concepts found
Transcript
Chapter 1
• Java
– Originally for intelligent consumer-electronic devices
– Then used for creating Web pages with dynamic
content
– Now also used for:
• Develop large-scale enterprise applications
• Enhance WWW server functionality
• Provide applications for consumer devices (cell phones, etc.)
1
PDA and Cell Phone
2
Java’s History
• James Gosling and Sun Microsystems
• Oak
• Java, May 20, 1995, Sun World
• HotJava
– The first Java-enabled Web browser
• Early History Website:
– http://en.wikipedia.org/wiki/Java_(programming_language)
– http://java.sun.com/features/1998/05/birthday.html
3
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
4
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Java is partially modeled on C++, but greatly
simplified and improved. Some people refer to
Java as "C++--" because it is like C++ but
with more functionality and fewer negative
aspects.
5
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Java is inherently object-oriented.
Although many object-oriented languages
began strictly as procedural languages,
Java was designed from the start to be
object-oriented. Object-oriented
programming (OOP) is a popular
programming approach that is replacing
traditional procedural programming
techniques.
One of the central issues in software
development is how to reuse code. Objectoriented programming provides great
flexibility, modularity, clarity, and
reusability through encapsulation,
inheritance, and polymorphism.
6
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Distributed computing involves several
computers working together on a network.
Java is designed to make distributed
computing easy. Since networking
capability is inherently integrated into
Java, writing network programs is like
sending and receiving data to and from a
file.
7
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
You need an interpreter to run Java
programs. The programs are compiled into
the Java Virtual Machine code called
bytecode. The bytecode is machineindependent and can run on any machine
that has a Java interpreter, which is part of
the Java Virtual Machine (JVM).
8
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Java compilers can detect many problems
that would first show up at execution time
in other languages.
Java has eliminated certain types of errorprone programming constructs found in
other languages.
Java has a runtime exception-handling
feature to provide programming support
for robustness.
9
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java implements several security
Java Is Robust
mechanisms to protect your system against
harm caused by stray programs.
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
10
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Write once, run anywhere
With a Java Virtual Machine (JVM),
you can write one program that will
run on any platform.
11
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Because Java is architecture neutral,
Java programs are portable. They can
be run on any platform without being
recompiled.
12
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
13
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Multithread programming is smoothly
Java's Performance integrated in Java, whereas in other
Java Is Multithreaded languages you have to call procedures
specific to the operating system to enable
Java Is Dynamic
multithreading.
14
Characteristics of Java
•
•
•
•
•
•
•
•
•
•
•
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java was designed to adapt to an evolving
Java Is Portable
environment. New code can be loaded on the
Java's Performance
fly without recompilation. There is no need for
Java Is Multithreaded developers to create, and for users to install,
major new software versions. New features can
Java Is Dynamic
be incorporated transparently as needed.
15
JDK Versions
•
•
•
•
•
•
•
JDK 1.02 (1995)
JDK 1.1 (1996)
JDK 1.2 (1998)
JDK 1.3 (2000)
JDK 1.4 (2002)
JDK 1.5 (2004) a. k. a. JDK 5 or Java SE 5
JDK 1.6(2006) a. k. a. JDK 6 or Java SE 6
16
JDK Editions
• Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone
applications or applets.
• Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications such as
Java servlets and Java ServerPages.
• Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile devices
such as cell phones.
This course uses J2SE to introduce Java programming.
17
Java IDE Tools
• Borland JBuilder
• NetBeans Open Source by Sun
• Sun ONE Studio by Sun MicroSystems
• Eclipse Open Source by IBM (preferred in
this course)
18
Introduction to Classes and objects
• Agenda
– What is an object oriented view of
programming?
– What is a class?
– How to define a class?
– Creating and using an object
19
What is an object oriented
view of programming
Suppose I want to invite my friends Tom, Liz and
Rita to meet me for coffee at Tim Horton’s in the
Devonshire Mall at 8PM today.
Approach 1:
Give a complete and very detailed set of
instructions on how to go from the University to
Tim Horton’s.
In this approach, every one exactly follows my
instructions.
20
What is an object oriented
view of programming
Approach 2:
Simply tell my friends “ Pl meet me for coffee at 8
this evening at Tim Horton’s in the Devonshire
Mall”
Here each person follows his/her own way of
interpreting my message and reacting to it.
I don’t know and I don’t care the specific
mechanism used by each individual in response to
my message.
21
A model for this approach
• Community of interacting agents called objects
• Each object provides services
• All action is initiated by a message to an object
22
Object oriented view
• Importance of information hiding
• Service oriented view of the world
23
Notion of classes and objects
My Cookie cutter
• Every time I use
the cookie cutter, I
get a cookie ready
for baking.
•Each cookie looks
exactly like the
others
•View my cookie
cutter as a
template
24
Class - a template for similar
objects
Class definition
• What are the properties of the class?
• What are the capabilities of the class?
Worker class
• How to characterise an object?
– name, age, place_working
• What can an object do?
– change the place of work
– describe the object as a string
25
Creating an object
• First step is to define the class if needed
• Use the class as a template to create
objects
• All objects of the same class has the
same set of properties and capabilities
26
Class Hierarchies and inheritance
Notion of superclass and subclasses
27
Defining a class
public class worker
{ String Name; // Example of a variable
int age;
String placeWorking;
public void ChangeJob(String NewPlace) // Method
{placeWorking = NewPlace;
}
// Other methods as needed
public worker(String WorkerName) // Constructor
{Name = WorkerName;
}
}
28
How to use the services of a class
• A service => a method
• An object of the class must exist for nonstatic
methods
worker w;
w = new worker( “Jim”);//use of constructor
• Use service => invoke right method
w. ChangeJob(“Ford, Windsor”);
29
Thinking About Objects
• Objects
– Reusable software components that model
real-world items
– Look all around you
• People, animals, plants, cars, etc.
– Attributes
• Size, shape, color, weight, etc.
– Behaviors
• Babies cry, crawl, sleep, etc.
30
Java Class Libraries
• Classes
– Include methods that perform tasks
• Return information after task completion
– Include variables defining properties of class
– Used to build Java programs
• Java contains class libraries
– Known as Java APIs (Application Programming
Interfaces)
– http://java.sun.com/j2se/1.5.0/docs/api/
31
Basics of a Typical Java Environment
• Java programs normally undergo five phases
– Edit
• Programmer writes program (and stores program on disk)
– Compile
• Compiler creates bytecodes from program
– Load
• Class loader stores bytecodes in memory
– Verify
• Verifier ensures bytecodes do not violate security
requirements
– Execute
• Interpreter translates bytecodes into machine language
32
Phase 1
Editor
Disk
Program is created in
an editor and stored
on disk in a file ending
with .java.
Phase 2
Compiler
Disk
Compiler creates
bytecodes and stores
them on disk in a file
ending with .class.
Primary
Memory
Phase 3
Class Loader
Disk
Phase 4
Bytecode
Verifier
. ..
..
.
Class loader reads
.class files
containing
bytecodes from
disk and puts
those bytecodes
in memory.
Primary
Memory
Bytecode verifier
confirms that all
bytecodes are valid
and do not violate
Java’s security
restrictions.
. ..
..
.
Primary
Memory
Phase 5
Interpreter
. ..
..
.
Interpreter reads
bytecodes and
translates them into
a language that the
computer can
understand,
possibly storing
data values as the
program executes.
Typical Java environment.
33
Compiling Java Source Code
You can port a source program to any machine with appropriate
compilers. The source program must be recompiled, however,
because the object program can only run on a specific machine.
Nowadays computers are networked to work together. Java was
designed to run object programs on any platform. With Java, you
write the program once, and compile the source program into a
special type of object code, known as bytecode. The bytecode
can then run on any computer with a Java Virtual Machine, as
shown below. Java Virtual Machine is a software that interprets
Java bytecode.
Java Bytecode
Java Virtual
Machine
Any
Computer
34
Thinking About Objects (60-322)
• Object-oriented design (OOD)
– Models real-world objects
– Models communication among objects
– Encapsulates attributes and operations (behaviors)
• Information hiding
• Communication through well-defined interfaces
• Object-oriented language
– Programming in object oriented languages is called
object-oriented programming (OOP)
– Java
35
Thinking About Objects
• Object-Oriented Analysis and Design
(OOA/D)
– Essential for large programs
– Analyze program requirements, then develop
solution
– UML
• Unified Modeling Language
36
• A First Program in Java: Printing a Line of Text
• Modifying Our First Java Program
• Displaying Text in a Dialog Box
•Another Java Application: Adding Integers
•Memory Concepts
•Arithmetic
•Decision Making: Equality and Relational Operators
37
A Simple Java Program
Listing 1.1
//This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
38
Creating and Editing Using NotePad
To use NotePad, type
notepad Welcome.java
from the DOS prompt.
39
Creating and Editing Using WordPad
To use WordPad, type
write Welcome.java
from the DOS prompt.
40
Creating, Compiling, and
Running Programs
Create/Modify Source Code
Source code (developed by the programmer)
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Byte code (generated by the compiler for JVM
to read and interpret, not for you to understand)
…
Method Welcome()
0 aload_0
…
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
5 invokevirtual #4 …
8 return
Saved on the disk
Source Code
Compile Source Code
i.e., javac Welcome.java
If compilation errors
stored on the disk
Bytecode
Run Byteode
i.e., java Welcome
Result
41
If runtime errors or incorrect result
Comments
In Java, comments are preceded by two slashes (//)
in a line, or enclosed between /* and */ in one or
multiple lines. When the compiler sees //, it ignores
all text after // in the same line. When it sees /*, it
scans for the next */ and ignores any text between /*
and */.
42
Discuss four small Java
programs
Welcome1.java
Welcome2.java
Welcome3.java
Welcome4.java
43
Displaying Text in a Message Dialog Box
you can use the showMessageDialog method in
the JOptionPane class. JOptionPane is one of
the many predefined classes in the Java system,
which can be reused rather than “reinventing
the wheel.”
44
The showMessageDialog Method
JOptionPane.showMessageDialog(null,
"Welcome to Java!",
“Display Message",
JOptionPane.INFORMATION_MESSAGE));
45
Two Ways to Invoke the Method
There are several ways to use the
showMessageDialog method. For the time being,
all you need to know are two ways to invoke it.
One is to use a statement as shown in the
example:
JOptionPane.showMessageDialog(null, x,
y, JOptionPane.INFORMATION_MESSAGE));
where x is a string for the text to be displayed, and
y is a string for the title of the message dialog box.
The other is to use a statement like this:
JOptionPane.showMessageDialog(null, x);
where x is a string for the text to be displayed.
46
The exit Method
Prior to JDK 1.5, you have to invoke
System.exit() to terminate the program if
the program uses JOptionPane dialog
boxes. Since JDK 1.5, it is not necessary.
47
Escape characters
– Backslash ( \ )
– Indicates special characters be output
Esc a p e
De sc rip tio n
se q ue nc e
\n
Newline. Position the screen cursor at the beginning of the
next line.
\t
Horizontal tab. Move the screen cursor to the next tab stop.
\r
Carriage return. Position the screen cursor at the beginning of
the current line; do not advance to the next line. Any
characters output after the carriage return overwrite the
characters previously output on that line.
\\
Backslash. Used to print a backslash character.
\"
Double quote. Used to print a double-quote character. For
example,
System.out.println( "\"in quotes\"" );
displays
"in quotes"
So m e c o m m o n e sc a p e se q ue nc e s.
48
Another Java Application: Adding Integers
Addition.java
Messa g e d ia lo g typ e
Ic o n
Desc rip tio n
JOptionPane.ERROR_MESSAGE
Displays a dialog that indicates an error
to the user.
JOptionPane.INFORMATION_MESSAGE
Displays a dialog with an informational
message to the user. The user can simply
dismiss the dialog.
JOptionPane.WARNING_MESSAGE
Displays a dialog that warns the user of a
potential problem.
JOptionPane.QUESTION_MESSAGE
Displays a dialog that poses a question to
the user. This dialog normally requires a
response, such as clicking on a Yes or a
No button.
JOptionPane.PLAIN_MESSAGE
no icon
Displays a dialog that simply contains a
message, with no icon.
JOptionPane c o nsta nts fo r m essa g e d ia log s.
49
Memory Concepts
• Visual Representation
– Sum = 0; number1 = 1; number2 = 2;
sum
0
– Sum = number1 + number2; after execution of
statement
sum
3
50
Arithmetic
• Arithmetic calculations used in most rograms
– Usage
• * for multiplication
• / for division
• +, • No operator for exponentiation (more in Chapter 5)
– Integer division truncates remainder
7 / 5 evaluates to 1
– Remainder operator % returns the remainder
7 % 5 evaluates to 2
51
Arithmetic
• Operator precedence
– Some arithmetic operators act before others (i.e.,
multiplication before addition)
• Use parenthesis when needed
– Example: Find the average of three variables a, b
and c
• Do not use: a + b + c / 3
• Use: ( a + b + c ) / 3
– Follows PEMDAS
• Parentheses, Exponents, Multiplication, Division, Addition,
Subtraction
52
Arithmetic
Op era to r(s)
*
/
%
+
-
Op era tio n(s) Ord er o f eva lua tio n (p rec ed enc e)
Multiplication Evaluated first. If there are several of this type of
Division
operator, they are evaluated from left to right.
Remainder
Addition
Evaluated next. If there are several of this type
Subtraction
of operator, they are evaluated from left to right.
Prec ed enc e o f a rithm etic o p era to rs.
53
Decision Making: Equality and
Relational Operators
Sta nd a rd a lgeb ra ic
eq ua lity or
rela tiona l op era tor
Equality operators
=

Relational operators
>
<


Ja va eq ua lity
or rela tiona l
op era tor
Exa mp le
of Ja va
c ond ition
Mea ning of
Ja va c ond ition
==
!=
x == y
x != y
x is equal to y
x is not equal to y
>
<
>=
<=
x > y
x is greater than y
x < y
x is less than y
x >= y
x is greater than or equal to y
x <= y
x is less than or equal to y
Eq ua lity a nd rela tiona l op era tors.
54
• Precedence of operators
Op era tors
* / %
+ < <= > >=
== !=
=
Prec ed enc e a nd
Assoc ia tivity
Typ e
left to right
multiplicative
left to right
additive
left to right
relational
left to right
equality
right to left
assignment
a ssoc ia tivity of the op era tors d isc ussed so fa r.
55