Freshers Week Java Course Part 2

mongooseriverDéveloppement de logiciels

7 juin 2012 (il y a 6 années et 9 mois)

483 vue(s)

Freshers Week Java Course
Part 2 Objects and Classes: Foundations
An Introduction to
Objects and Classes in Java
Dr.-Ing. Norbert Völker
Lab Assistant: Roxanna Turner
Rectangle Area – Procedural Style
Procedural Programming
 Procedural programming
public class RectangleArea {
 procedures that implement tasks
public static void main(String [] args) {
 sequence: read input, perform computations, change
double x1 = 1.0, y1 = 3.0, x2 = 3.0, y2 = 6.0;
state, return output
showRectangleArea(x1, y1, x2, y2);
 breakdown into smaller and smaller tasks
public static void showRectangleArea(double x1, double y1,
double x2, double y2) {
 control structures: sequencing, if-then-else, …
double area = Math.abs((x2 - x1) * (y2 - y1));
System.out.println("Rectangle [(" + x1 + "," + y1 + "),(" + x2 + ","
 Rectangle area calculation + y2 + ")] has area " + area);
The Idea behind the OO Approach Class Diagram Rectangle
 Define objects and classes in programming by abstracting
from real-world entities
Rectangle class name
 a “class” is a category of objects
 rectangles, cars, students, …, buffers, actions, … x1
 an object is an element of a class
(“data”, “state”)
 this rectangle, John’s car, a particular student, ...
 models one particular entity
 In Java, each object is an instance of exactly one class
1Two Objects Object Identity and State
 Every object has an identity
 Corresponds to reality.
r1 : Rectangle r2 : Rectangle
 My car” is different from “your car” even if it has the
same attributes (registration number, make, year, etc)
x1= 1.0; x1 = -1.0
y1 = 3.0 y1 = 2.0  Objects have a state
 Given by the current value of the attributes
x2 = 3.0 x2 = -4.0
y2 = 6.0 y2 = 1.0  Typically some attributes vary while others stay fixed
 Class Rectangle might be used in a drawing program
 coordinates can change as the rectangle is moved
around, stretched or shrunk
Methods OO Approach Remarks
 Methods allow  Break system down into objects/classes
 creation of objects, changing object state, finding out  Your classes should model relevant aspects of reality
information about objects
 a “student” object in a Java program only reflects
 methods can call other methods! certain aspects of real students
 Class Rectangle currently only defines introspection  you need to decide what aspects are needed in your
methods program
 no methods for changing state as yet  Class definitions should aim for reusability
 class Rectangle can be used in many different
 add a method for moving rectangle horizontally
public void moveX (double x) { …}
 include those methods which are expected by other
developers who will be using your class
Using Objects in Java
class Geometry {
The Beginnings of Programming
public static void main(String[] args) {
with Objects and Classes in Java
Rectangle r1; // declaration of variable
r1 = new Rectangle (1.0, 3.0, 3.0, 6.0);
System.out.println(r1 + " has area " + r1.area());
Exercise: draw a class diagram for class Geometry.
2Assigning a New Object Aliasing
 Describe the effect of method call
r1 = new Rectangle (1.0, 3.0, 3.0, 6.0);
 creates a new Rectangle object by calling a “constructor”
and assigns it to variable r1
 Suppose we add the code below at the end of method
Geometry.main() ? What would be output?
Rectangle r2 = r1;
r1 y1=3.0
r1 = new Rectangle (0,0,0,0);
 You can join a variable declaration with an assignment into
a single “initialization” statement:
Rectangle r1 = new Rectangle (1.0, 3.0, 3.0, 6.0);
Encapsulation Implementation:
 We have used Rectangle objects without knowing about
Attributes are also known as
the implementation of the class.
“instance variables” in Java
public class Rectangle {
 This is an example of encapsulation
double x1, x2, y1, y2;
 Information about how an object solves tasks is
hidden inside the object.
Rectangle (double x1, double y1, double x2, double y2) { …}
 Similar to “procedural abstraction” – you only need to
double area() { … }
know a procedure signature to call it, not how it is
public String toString() {… }
public void moveX (double x) { …}
Attributes Method Implementation
 Attributes are realized in Java as instance variables. double area() { return (Math.abs((x2 - x1) * (y2 - y1))); }
 Also called the “fields” of the class.
public String toString() {
 The type of an instance variable can either be
return "Rectangle [(" + x1 + "," + y1 + "),(" + x2 + "," + y2 +
 one of the eight primitive types in Java (byte, short, int,
")]"; }
long, float, double, char, boolean) or
 a reference type
public void moveX (double x) {
 this is used to refer to objects x1 += x;
x2 += x; }
 Note the difference between parameters and attributes
in method moveX().
 Do you know the meaning of “void” ?
3Constructors Constructor Implementation
 For the code above to work, the Java class Rectangle
Rectangle (double x1, double y1, double x2, double y2) {
must have a constructor method
this.x1 = x1;
Rectangle (double x1, double y1, double x2, double y2)
this.y1 = y1;
this.x2 = x2;
 The name of the constructor method is the same as the
name of the class. this.y2 = y2;
 Same as the result type of the constructor.
 In UML class diagrams, constructor methods are often
not shown.  The use of “this” in order avoids a name clash between
attributes and parameters.
 Could also use parameter names that differ from
attribute names.
Static Attributes and Methods Constants
 Static attributes belong to the class, not particular objects
 It is bad programming style to use hard coded numbers
 have the same value for each object of the class
in your code.
 For class Rectangle, we could add a static field count that
if (numberOfStudents > 100) { ….};
is intialized with 0 and is incremented by 1 whenever a
 It is better to use variables, for example:
new rectangle is created.
double maxCourseSize = 100;
 Static methods (also called “class” methods) do not refer
if (numberOfStudents > maxCourseSize) { …}
to a particular object.
 Constants can be declared as static final fields in a class.
public static double sqrt(double number)
This protects against unwanted changes.
double sqrtTwo = Math.sqrt(2); //usage
public static final maxCourseSize = 100;
 Question: normal “instance method” call or static call?
 From outside the class, access needs a prefix:
System.out.println("Now Sort Array");
double circumference = Math.PI * 2 * radius;
 A variable of a reference type may be set to null.
This means that it does not refer to any object.
if (errorInInput) Student nextStudent = null;
 You can check if the current value of a variable is null.
 This is useful as some methods return null if they are
not able to return a valid object.
Libraries and code organisation.
For example, showInputDialog returns null if the user
hits the “Cancel” button.
String input = JOptionPane.showInputDialog(
“Please enter account number”);
if (input == null) …
4Java Library Packages Import Statements
 Java library classes are organised in packages.
 The import statement makes classes accessible without
having to use the full long name, for example:
import java.util.Random
java.lang, java.util,, java.util.regex
class TestRandom {
public static void main (String[]args) {

Random rGen = new Random(seed); …} }
 java.lang entities are automatically known to the compiler.
 Import statements must be placed before any class
 The full name of class String is java.lang.String
declarations in the .java file,.
 The large number of libraries in J2SE is one of the main
reasons behind the popularity of Java.  A file can have several import statements.
 Exercises will make use of classes in java.util :
 You can also import all classes from a package in one go:
import java.util.*
 and possibly ArrayList and TreeSet
More on Import Packages and Directory Structure
 Care has to be taken that this does not lead to a collision:  All the .class files belonging to one package need to be in
different packages might contain classes with the same the same directory.
 The directory structure needs to correspond to the
 Example [Eckel]: package structure
import com.bruceeckel.simple.*;  For a package called “freshersWeek”, the files should
be in directory “freshersWeek”
import java.util.*;
 For a package “ce832.exercises”, there should be a
The compiler will complain in this case if you try to
directory “ce832” with a subdirectory “exercises”.
create a new object of class Vector as it does not know
which Vector class is meant.  etc.
 Without the import, there is no clash:
java.util.Vector x = new java.util.Vector();
Packages: Compiling and Running Organising your Own Classes
 In order to compile from the command prompt, change  It is easiest to put all your java source files into one
to the root directory of the package. directory and compile them with: javac *.java
cd /ufs/csstaffc/users/norbert/src/  BUT: putting all files into one directory is bad practice
for larger projects.
javac ce832/utilities/*.java
 Use packages in order to group classes together.
 Running method ce832.utilities.MyRandom.main():
package ce832.utilities;
java ce832.utilities.MyRandom
public class MyRandom {
 For usage of the CLASSPATH environment variable, see
the online Java tutorial, section packages. // …
 Check out Java IDEs (NetBeans, Eclipse, IntelliJ, …)  The package declaration needs to be right at the start of
the .java file.
 many advantages
 do not move source files on the disk while the IDE is
running (use IDE refactor/renaming instead)
5Java Collections are Generic Literature
 Java API Documentation
 Online Java Tutorial
 Cay Horstmann, Big Java, Wiley.
 Class ArrayList<E>
 H.M. Deitel and P.J. Deitel: Java – How to program,
 Class TreeSet<E>
 Bruce Eckel: Thinking in Java (Online available)
 These are generic classes
 And many others!
 Type variable E stands for the collection elements
 Can be substituted with other types in applications  Java 5 saw significant changes to the language, in
 For example, you could have particular the introduction of generics.
 Differences between Java 6 and Java 5 are mainly on
the level of libraries and implementation improvements.
 The Java API documentation is your friend