Вы находитесь на странице: 1из 15

EE2422 Objects Orientated Programming

Course Content
EE2425 • Review of OOP Fundamentals

Objects Orientated
• Overview of Java and the BlueJ Environment
•Java Language basics

Programming • Understanding class definitions


• Abstraction and Modularization
Module Tutor: David Styles. • Grouping Objects
Webpages: • Using libraries
www.staff.city.ac.uk/~sf323/ • Designing, testing & debugging classes
• Polymorphism
Email: d.j.styles@city.ac.uk
• Using Inheritance
Room C138. • Error Handling
Tel: 020 7040 8124 2.0
• Java Applets 2

Recommended Books Recommended Books


Objects First with Java Java for Students
A Practical Introduction using BlueJ Douglas Bell & Mike Parr
David J. Barnes & Michael Kölling Publisher: Pearson / Prentice Hall
Publisher: Pearson / Prentice Hall ISBN 0-13-124618-6
ISBN 0-13-044929-6. Price £35
Price £31

Java in easy steps


Mike McGrath
ISBN 1-84078-259-5
Publisher Computer Step
Price £10.99`
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 3 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 4
Recommended On-line support Recommended On-line support
BlueJ / Objects First support Introduction to Programming
www.bluej.org Using Java
Download site for BlueJ IDE David J. Eck
http://www.bluej.org/download/download.html Hobart and William Smith Colleges. New York
A very useful on-line text book

http://math.hws.edu/javanotes/

Java Tutorials
Sun Microsystems created Java and have an
excellent on-line reference known as Java Tutorials
Updated http://java.sun.com/docs/books/tutorial/
Slide
25/02/10 http://java.sun.com/docs/books/tutorial/reallybigindex.html5 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 6

Review of the fundamental Notes

concepts of OOP
All OOP languages adhere to the following key
principles: -

• Encapsulation
• Polymorphism
• Inheritance
Please review the definitions for these given in
computer technology 2 module.
In this module we will implement all three of
these principles
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 7 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 8
Review of the fundamental concepts of OOP Review of the fundamental concepts of OOP

Objects and Classes Objects and Classes


• Objects (Often referred to as an instance of a class) Defining a Class
– represent instances from the real world, or from
some problem domain
Example:
“The red car down there in the car park”
The red car is an instance of a car
• Classes
– represent a framework in which all objects of a
Let’s create a class
particular kind are defined that defines a Car
Example: “Car” Does not refer to a specific instance
• Classes contain all values and implementation
code associated with an object of that class
This is Encapsulation
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 9 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 10

Notes
Review of the fundamental concepts of OOP
Objects and Classes
• Most modern programming languages are
based upon Object Orientated Programming
techniques.
• Applications are designed around the Objects
that are used.
• Code and data for a particular Object is
Encapsulated within Classes.
– A Class is a complex data type that can contain
both data (fields/properties) & functions (methods)
– Generally Classes are not used directly, instead an
instance (copy) is made.
– An Object is an instance of a particular Class.
Objects–First
Many
with Java instances may
- A Practical Introduction usingbe
BlueJ,created from
© David J. Barnes, a Kölling
Michael single class
11 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 12
Objects and Classes Review of the fundamental concepts of OOP

Form1 is an Object:
Properties & Fields
Created from the • These define what values or parameters
Jframe Class.
are associated with the class.
label1 is an Object: – Each object has it’s own set of values
Created from the
Jlabel Class. known as the state of the object.
button1 is an Object: – These are known as instance values or
Created from the instance variables.
Jbutton Class.
– They are Encapsulated into a class and only
act upon a specific Object of that class.
Jframe Form1 = new Jframe(“Form1”); i.e That is each Object has it’s own
Jlabel label1 = new Jlabel(); independent copy of these variables.
Updated
Slide Jbutton button1 = new Jbutton(); 13
Updated
Slide Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 14
28/01/10 28/01/10

Review of the fundamental concepts of OOP Notes


Propeties & Fields
Instance values
Creating Objects
from classes

Updated
Slide
Example:Two circle objects
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 15 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 16
28/01/10
Review of the fundamental concepts of OOP Review of the fundamental concepts of OOP

Methods Methods
• As well as values, Classes can must also Method Declaration – Optional
contain implementation code General Form parameters
scope return_type MethodName(type Arg1, type Arg2,..)
• This code is contained within special {Implementation code; //Java code to perform required task
functions called Methods. return (return_type); //Returns value (optional)
}
• Methods should only act upon the • scope: public, private, protected, etc
specific instance of the class in which it • return_type: void, int, char, String, etc
was invoked. • parameters: are values that can be passed
• As with functions, Methods may receive when method is called (they are local variables).
arguments, or return a value. – type: void, int, char, String, etc
Updated Updated
Slide
17
Slide – Arg1,Arg2: Name assigned to argument.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 18
28/01/10 28/01/10

Review of the fundamental concepts of OOP Notes


Objects and Classes
Method and Field Declaration
public class Car
{
public String Make,Model,Colour; // Properties / Fields
private int NumberOfDoors; // Property / Field
private float EngineSize; // Property / Field

public void SetDoors(int doors) // Method


{ if (doors<6 && doors >1 ) NumberOfDoors=doors;
}

public int GetDoors(); // Method


{ return(NumberOfDoors); // Method implementation
}

public abstract void SetEngine(float engine); // Method


public abstract float GetEngine(); // Method
}
Updated // Note that the Abstract Methods contain no Implementation Code
Slide Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 19 20
28/01/10
Review of the fundamental concepts of OOP Review of the fundamental concepts of OOP
Objects and Classes Objects and Classes: Scope
Scope • Java provides five levels of visibility:-
• Provides the ability to specify the – Public: Visible from both inside & outside
of class.
degree of visibility of fields and
methods. – Private: Visible only within class.
– Hides detail of implementation. – Local: Visible only within the method in
which it has been declared.
– Protects access to class members.
– Package: Outer layer in which access to
– Allows names to be reused outside of class. public class members is restricted
• Provides basis for Encapsulation to within package (default scope)
– Protected: Public access extended to child
21
classes outside package.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 22

Review of the fundamental concepts of OOP Notes

Scope Example
public class Car Visible from
{ outside of class
public String Make,Model,Colour;
private int NumberOfDoors; Only visible
private float EngineSize; from inside class
public void SetDoors(int doors)
{ if doors<6 && doors >1 NumberOfDoors=doors;}
Allows indirect
public int GetDoors(); access to
{ return(NumberOfDoors);}
NumberOfDoors
public abstract void SetEngine(float engine);
public abstract float GetEngine();
}Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 23 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 24
Review of the fundamental concepts of OOP Review of the fundamental concepts of OOP

Constructors Creating an Object or instance


• General Form Constructor
• Special method used to create instances
ClassName InstanceName = new Classname();
• Designer can include code within
constructor to customize object. Example: Creating instances of the Car class
• Constructor Car MyCar = new Car();
– shares same name as class. Car AnotherCar = new Car();
– Can receive parameters Car YetAnotherCar = new Car();
– Cannot return values …
MyCar.Make=“Skoda”; //Set Make field of object MyCar
• General Form
MyCar.Colour=“Red”; //Set Colour field of object MyCar
scope ClassName(type Arg1, type Arg2,..) AnotherCar.Make=“Lexus”;
{ Source code; //Java code to perform required task AnotherCar.Colour=“Silver”;
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 25 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 26

Notes
Overview of Java
and the BlueJ IDE
• Characteristics of the Java language
– Java history
– What’s different about Java?
– Java program structure
– Writing java from scratch
• Introduction to BlueJ
• Java language basics

27 28
Characteristics of the Characteristics of the Java language
Java History
Java language • 1991:First launched as a OOP language
• Developed by Sun Microsystems for embedded hardware applications.
• Object Orientated language based on C++ Not very popular. Project was endanger of collapse
• First language developed specifically for web. • 1993: Explosion in internet use allowed
• First truly platform independent language. Sun to re-develop Java for use dynamic
• Open source. Web pages.
– Download www.java.sun.com • 1995: Java re-launched for Web
• Hybrid interpreted and compiled modes development
• Computational speed(?) – Java now the principle language used to
– Slower than true compiled language create web pages that have interactive
content.
29 – Also popular for smartcard applications30

Characteristics of the Java language Notes


Java variations
• Java Development Kit (JDK) – Sun Micro systems
– Original Java command line tools
• Originally programs developed using notepad
• No IDE
• Still preferred method by purists.
– JavaBeans
• Sun’s own IDE development tool
• JBuilder – Borland
– Simple IDE – Not drag & drop.
– Code not 100% compactable with Java.
• J#.NET (pronounced J Sharp)
– Very sophisticated IDE
• Full drag & drop capability
• Applications may comprise of different language segments
• Java
Objects First with Transparent internet/web
- A Practical Introduction interface
using BlueJ, © David J. Barnes, Michael Kölling 31 32
What’s different about Java? What’s different about Java?
Application environments The Java Virtual Machine (JVM)
• Java was the first language to incorporate the
• Console applications concept of the virtual machine
– Basic command line support
– DOS window only (e.g no GUI) Java
Java Java
Java
Java
Java
Source Object
• GUI applications Source
Code
Compiler
Compiler
Object
Code
Code Code
– e.g. menus, toolbars, buttons, mouse
control etc
• Applets
– Enables code to be directly embedded in a Java
Javavirtual
virtualmachine
machine(JVM)
(JVM) Computer
Computer
web page Java
operating
operating
Javainterpreter
interpreter
Java was first language that had a
system
system

program structure specifically for web


Virtual
•Objects machine allows true application portability34
development.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
33 First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

What’s different about Java? Notes


The Java Virtual Machine (JVM)
• All Java code is executed within JVM.
– No directly executable native code file.
• Java compiler converts Java mnemonics into
intermediate-code (known as Object or Byte code)
• JVM acts as interpreter and converts this to
native code for the platform.

Java
Java
Hello.java
Hello.java Hello.class
Hello.class
Compiler
Compiler

– Source code files *.java


– Object code files *.class
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 35 36
Java Program Structure Java Program Structure
Console Program structure GUI application structure
HelloWorld.java
HelloWorld.java
import javax.swing.*; // Java windows library
public class HelloWorld
class SwingWindow extends Jframe
{ {
public static void main (String[] args) public SwingWindow() //Constructor
{ {
super("Hello World"); // Text that appears in frame
System.out.println("Hello World"); setSize(300,100);
} setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // Make frame visible
} }
• Command line application public static void main (String[] args)
– Text appears in DOS window. { // Create instance of SwingWindow Class called Hello
SwingWindow Hello = new SwingWindow();
– Cannot use standard GUI objects }
• Main method indicates primary class }
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 37 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 38

Java Program Structure Notes


Writing Java from scratch
• Traditionally Java programs have been
created using text editors such as notepad.
• The following JDK command line tools are
available
– Javac SourceFile.java //Compiles source file
Example javac Hello.java
– Java ClassName //Executes program within JVM
Example javac HelloWord

• For full details on JDK tools see java tutorials.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 39 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 40
Introduction to BlueJ Java Language basics
As Java is based on C++ much of the language
• Developed at the University of Southern most syntax should be familiar.
Denmark specifically for the purpose of • Primitive data types
teaching OOP. • Overview
• Casting between primitives
• Provides a simple IDE for Java.
• Operators
– Uses Sun JVM
• Therefore no compatibility problems
– Arithmetic and Assignment operators
• Requires JDK to be present on machine – Relational
• Does require addition of main method to run – Logical
standalone.
– Other Java operators
– Free download available • Control flow statements
– On-line support. • Class-based data types
Objects First with JavaNow try
- A Practical exercise
Introduction using BlueJ, © 2 inJ. Barnes,
David first lab
Michael …
Kölling 41 • Characters & Strings
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 42

Java Language basics Notes


Primitive Data types
As Java is based on C++ much of the
language syntax should be familiar.
Each variable comprises of :-
• primitives (Same as C)
ƒ byte, short, int, long, float, double
ƒ char Single Unicode character (‘a’)
ƒ Boolean e.g. true or false
• user defined identifier (e.g. MyVariable)
ƒ are case sensitive
ƒ cannot start with a number or operator.
ƒ rest of identifier any chars except operators
ƒ keywords
Objects First with cannot
Java - A Practical Introduction be
using used
BlueJ, © Davidas identifier
J. Barnes, Michael Kölling 43 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 44
Java Language basics Java Language basics
Primitive data types (similar to C) Final variables
Type Size in Va lues Sta ndard
bits The value of a final variable cannot change after it
boolean 8 true or false has been initialized. Such variables are similar to
char 16 ’\u0000’ to ’\uFFFF’ (ISO Unicode
character set)
constants in C.

Example:
byte 8 –128 to +127
short 16 –32,768 to +32,767
int 32 –2,147,483,648 to
+2,147,483,647
final int MyAge = 21;
long 64 –9,223,372,036,854,775,808 to int Age=0;
+9,223,372,036,854,775,807
float 32 –3.40292347E+38 to (IEEE 754 floating

double
+3.40292347E+38
–1.79769313486231570E+308
point)
(IEEE 754 floating
Age++; //Variable Age would be incremented
64 to
+1.79769313486231570E+308
point) MyAge++; //This would produce a compiler error
Note: Float values out of range are return ± infinity
Non numerical values return NaN (Not a Number)
Note: As with C there is no String data type.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 45 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 46

Java Language basics Notes


Casting between primitives
byte short int long float double
• Java implements type promotion
Not required if resolution increased
Example: Which of the following cast operations are
wrong, and which unnecessary?
int i=5; short int s=216;
float f=5.25;
double d=5.25753;
d=(float)i;
i=(int)d;
d=(double)f;
f=(float)d;
i=(int)s;
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 47 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 48
Java Language basics Java Language basics
Operators Operators
• Arithmetic and Assignment • Arithmetic and Assignment Operators
– Multiplication – Addition
• A=A*B;
Not required if resolution increased • A=A+B;
Not required if resolution increased
• A*=B;//Shorthand for A=A multiplied by B assignment • A+=B; //Shorthand for A=A+B assignment
• A++ //A is incremented after statement evaluation
– Division • ++A //A is incremented before statement evaluation
• A=A/B; //A=A÷B – Subtraction
• A/=B //Shorthand for A=A÷B assignment • A=A-B;
• A%B //Remainder from A/B (Modulas) • A-=B; //Shorthand for A=A-B assignment
• A-- //A is decremented after statement evaluation
See Java tutorial webpages for more details • --A //A is decremented before statement evaluation
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 49 See
Objects First Java
with Java - tutorial webpages
A Practical Introduction usingfor
BlueJ,more
© Daviddetails
J. Barnes, Michael Kölling 50
www.java.sun.com/docs/books/tutorial/java/nutsandbolts/arithmetic.html

Java Language basics Notes


Operators
• Relational
– Compares two values and determines the
relationship between them.
– Returns either true or false.
Operator Use Returns true if
> op1 > op2 op1 is greater than op2
>= op1 >= op2 op1 is greater than or equal to op2

< op1 < op2 op1 is less than op2


<= op1 <= op2 op1 is less than or equal to op2
== op1 == op2 op1 and op2 are equal
!= op1 != op2 op1 and op2 are not equal

See Java tutorial webpages for more details


www.java.sun.com/docs/books/tutorial/java/nutsandbolts/relational.html
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 51 52
Java Language basics Java Language basics
Operators Operators
• Logical • Other
Operator Description
Operator Use Logical Operation (bitwise)
& op1 & op2 AND Shortcut if-else statement
| op1 | op2 OR ?: x =op1 ? op2 : op3 equivalent to
op1 ^
^ op2
XOR if(op1== true) x=op2; else x=op3
~ ~op2 Complement (invert) [] Array delimiter / index
. Used to Access class and object members
• Shift ( Arg1,Arg2,...) Denotes Method parameters
Operator Use Operation (bitwise)
( type ) Casts (converts) a value to the specified type
>> op1 >>
op2
shift bits of op1 right by distance op2

<< op1 <<


op2
shift bits of op1 left by distance op2 new Creates a new object or a new array
instanceof
>>> op1 >>>
op2
shift bits of op1 right by distance op2 (unsigned)
op1 instanceof op2 checks if op1 is instance of op2 class

See Java tutorial webpages for more details See Java tutorial webpages for more details
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
53 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
54
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/bitwise.html http://java.sun.com/docs/books/tutorial/java/nutsandbolts/other.html

Java Language basics Notes


Control flow statements
Statement Type Keyword
Iterative (looping) while, do-while , for
Conditional (Decision making) if-else, switch-case
exception handling try-catch-finally, throw
break, continue, label:, return
•branching
Java Iterative & Conditional statements
– Share the same syntax as C.
– Review Computer Tech2 notes.

• Java exception handling


– Covered later in this module.
See the following Java tutorial webpages for more details
java.sun.com/docs/books/tutorial/java/nutsandbolts/flowsummary.html
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 55 56
Java Language basics Java Language basics
Control flow statements Control flow statements
Unconditional branch statements Unconditional branch statements
• break statement (already used in switch-case) • break & continue statement examples
– break; Terminates the innermost block of a conditional for(int loop=0; loop<100; loop++)
or loop statement. {
– break label; Terminates block specified by label if(loop==57) break;
• continue statement System.out.println(loop);
}
– continue; Terminate current iteration of loop and
evaluates associated relational operator. for(int loop=0; loop<100; loop++)
– continue label; As above but with respect to loop with {
given label if(loop==57 continue;
System.out.println(loop);
• return statement
}
– Same use and syntax as in C.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 57 What is the difference in the output produced
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 58
java.sun.com/docs/books/tutorial/java/nutsandbolts/flowsummary.html

Slide
Added
Java Language basics Notes
4/2/10
Input/Output Methods
• Among the facilities provided by the Java System class are
methods that allow the user to access the standard input , and
standard output streams of the computer These are typically
Keyboard and Display.
Output: System.out.println() methods:
A series of overloaded methods that allows data of most
common types to be displayed on the standard output device.
System.out.println(value to be displayed);

Input: System.in.read() methods: include:-


System.in.read(byte)
returns a single byte of data from the standard input device.
For more information about Input and Output methods available see :-
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#method_summary
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 59 60

Вам также может понравиться