Vous êtes sur la page 1sur 54

SOFE 2710: Object Oriented Programming

and Design

Instructors:
Anwar Abdalbari, PhD

Fall 2018
Faculty of Engineering and Applied Science
Object-Oriented Programming
and Problem Solving
Lecture Overview

 What is Object Oriented Programming?


 What is Java?
 Java Program Structure.
 The Java Syntax.
 To compile and run your first Java program
 To recognize compile-time and run-time errors
 Object Oriented Programming and Problem
Solving.
 To describe an algorithm with pseudocode
Java

 A programming language specifies the words and


symbols that we can use to write a program

 A programming language employs a set of rules that


dictate how the words and symbols can be put
together to form valid program statements

 The Java programming language was created by Sun


Microsystems, Inc.

 It was introduced in 1995 and it's popularity has


grown quickly since
Java Program Structure

 In the Java programming language:


• A program is made up of one or more classes
• A class contains one or more methods
• A method contains program statements

 These terms will be explored in detail throughout the


course

 A Java application always contains a method called


main
•Simple •Architecture neutral
•Object oriented •Portable
•Distributed •High performance
•Multithreaded •Robust
•Dynamic •Secure
Objects
 An object has:
• state - descriptive characteristics
• behaviors - what it can do (or what can be done to it)

 The state of a bank account includes its account


number and its current balance
 The behaviors associated with a bank account
include the ability to make deposits and withdrawals
 Note that the behavior of an object might change its
state
Classes

 An object is defined by a class


 A class is the blueprint of an object
 The class uses methods to define the behaviors of
the object
 The class that contains the main method of a Java
program represents the entire program
 A class represents a concept, and an object
represents the embodiment of that concept
 Multiple objects can be created from the same class
Class = Blueprint

One blueprint to create several similar, but different, houses:


Computer Programs

• Computers are programmed to perform many different tasks.


• Computers execute very basic instructions in rapid
succession.
• A computer program is a sequence of instructions and
decisions.
• Programming is the act of designing and implementing
computer programs.
• The physical computer and peripheral devices are collectively
called the hardware.
• The programs the computer executes are called the software.
Problem Solving

 The purpose of writing a program is to solve a


problem
 Solving a problem consists of multiple activities:
• Understand the problem
• Design a solution
• Consider alternatives and refine the solution
• Implement the solution
• Test the solution

 These activities are not purely linear – they


overlap and interact
Problem Solving (Cont’d)

 The key to designing a solution is breaking it


down into manageable pieces
 When writing software, we design separate
pieces that are responsible for certain parts of
the solution
 An object-oriented approach lends itself to this
kind of solution decomposition
 We will dissect our solutions into pieces called
objects and classes
Self Check 1.1

• What are the two most important benefits of the Java


language?
Answer: Safety and portability.
The Java Programming Language

 Safe
 Portable
 Platform-independent
• Distributed as instructions for a virtual machine
 Vast set of library packages
 Designed for the Internet
Java Program Structure

 In the Java programming language:


• A program is made up of one or more classes
• A class contains one or more methods
• A method contains program statements
 These terms will be explored in detail throughout the
course
 A Java application always contains a method called
main
 See HelloPrinter.java
Becoming Familiar with Your Programming
Environment

 An editor is a program for entering and modifying


text, such as a Java program.
 Java is case sensitive.
 Java compiler translates source code into class
files.
 Class files contain instructions for the Java virtual
machine.
C++ Programming Language

 Another object-oriented programming language


 Also widely used
 C++ was adopted as an object-oriented extension to C
 Some significant differences exist compared with Java
First Program in C++
• #include <stdio.h>
• // The HelloWorld class definition.
class HelloWorld {
public:
HelloWorld() {} // Constructor.
~HelloWorld() {} // Destructor.
void print() {
printf("Hello World!\n");
}
};

• // The main program.


int main() {
HelloWorld a; // Create a HelloWorld object.
a.print(); // Send a "print" message to the object.
return 0;
}
First Program in Java
Compiling and Running a Java Program
Java Translation

 The Java compiler translates Java source code


into a special representation called bytecode
 Java bytecode is not the machine language for
any traditional CPU
 Another software tool, called an interpreter,
translates bytecode into machine language and
executes it
 Therefore the Java compiler is not tied to any
particular machine
 Java is considered to be architecture-neutral
From Source Code to Running Program

File.java File.class
Development Environments

 There are many programs that support the


development of Java software, including:
• Java Development Kit (JDK)
• Eclipse
• NetBeans
• BlueJ
• jGRASP

 Though the details of these environments differ, the


basic compilation and execution process is essentially
the same
Syntax and Semantics

 The syntax rules of a language define how we


can put together symbols, reserved words, and
identifiers to make a valid program
 The semantics of a program statement define
what that statement means (its purpose or role
in a program)
 A program that is syntactically correct is not
necessarily logically (semantically) correct
 A program will always do what we tell it to do,
not what we meant to tell it to do
Errors
 A program can have two types of errors
 The compiler will find syntax errors and other basic
problems (compile-time errors)
• If compile-time errors exist, an executable version of the program
is not created

 A problem can occur during program execution, such as


trying to divide by zero, which causes a program to
terminate abnormally (run-time)

• Logical Errors
Errors (Cont.)

 Exception - a type of run-time error


• Generates an error message from the Java virtual
machine
• This statement
System.out.println(1 / 0)
• Generates this run-time error message
"Division by zero"
Self Check 1.2

• Suppose you change println to printline in the


HelloPrinter.java program. Is this a compile-time
error or a run-time error?

Answer: This is a compile-time error. The compiler will


complain that System.out does not have a method
called printline.
Self Check 1.3

• Suppose you change main to hello in the


HelloPrinter.java program. Is this a compile-time
error or a run-time error?

Answer: This is a run-time error. It is perfectly legal


to give the name hello to a method, so the compiler
won't complain. But when the program is run, the
virtual machine will look for a main method and won't
find one.
Self Check 1.4
• When you used your computer, you may have
experienced a program that "crashed" (quit
spontaneously) or "hung" (failed to respond to your
input). Is that behavior a compile-time error or a run-
time error?

Answer: It is a run-time error. After all, the program had


been compiled in order for you to run it.
Self Check 1.5

• Why can't you test a program for run-time errors


when it has compiler errors?

Answer: When a program has compiler errors, no class file


is produced, and there is nothing to run.
Becoming Familiar with Your
Programming Environment

 Start the Java development environment.


 Write a simple program.
 Run the program.
 Organize your work.
Output
//********************************************************************
// HelloPrinter.javaHelloAuthor:
World!Lewis/Loftus
// This is your 1st Program in Java.
// Demonstrates the basic structure of a Java application.
//********************************************************************

public class HelloPrinter


{
//-----------------------------------------------------------------
// Prints a presidential quote.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("Hello World!");

System.out.println ("This is your 1st program in Java.");


}
}
Java Program Structure

// comments
about the class

class header

class body

Comments can be placed almost anywhere


Comments

 Comments should be included to explain the


purpose of the program and describe processing
steps
 They do not affect how a program works
 Java comments can take three forms:
// this comment runs to the end of the line

/* this comment runs to the terminating


symbol, even across line breaks */

/** this is a javadoc comment */


Identifiers

 Identifiers are the "words" in a program


 A Java identifier can be made up of letters, digits,
the underscore character ( _ ), and the dollar sign
 Identifiers cannot begin with a digit
 Java is case sensitive: Total, total, and TOTAL are
different identifiers
 By convention, programmers use different case
styles for different types of identifiers, such as
• title case for class names - Lincoln
• upper case for constants - MAXIMUM
Identifiers (Cont.)

• Sometimes the programmer chooses the identifier


(such as Lincoln)
• Sometimes we are using another programmer's
code, so we use the identifiers that he or she chose
(such as println)
• Often we use special identifiers called reserved
words that already have a predefined meaning in
the language
• A reserved word cannot be used in any other way
Reserved Words

• The Java reserved words:


abstract else interface switch
assert enum long synchronized
boolean extends native this
break false new throw
byte final null throws
case finally package transient
catch float private true
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfp
double int super
Quick Check

Which of the following are valid Java identifiers?


grade
quizGrade
NetworkConnection
frame2
3rdTestScore
MAXIMUM
MIN_CAPACITY
student#
Shelves1&2
Quick Check

Which of the following are valid Java identifiers?


grade Valid
quizGrade Valid
NetworkConnection Valid
frame2 Valid
3rdTestScore Invalid – cannot begin with a digit
MAXIMUM Valid
MIN_CAPACITY Valid
student# Invalid – cannot contain the '#' character
Shelves1&2 Invalid – cannot contain the '&' character
White Space

 Spaces, blank lines, and tabs are called white


space
 White space is used to separate words and
symbols in a program
 Extra white space is ignored
 A valid Java program can be formatted many ways
 Programs should be formatted to enhance
readability, using consistent indentation
Analyzing Your First Program: Class Declaration

 Classes are the fundamental building blocks of Java


programs:
 Declaration of a class called HelloPrinter
• public class HelloPrinter
 In Java, file can contain, at most one public class.
every source
 The name of the public class must match the name
of the file containing the class:
• Class HelloPrinter must be contained in a file named
HelloPrinter.java
Analyzing Your First Program: Methods

 Each class contains declarations of methods.


 Each method contains a sequence of instructions.
 A method contains a collection of programming
instructions that describe how to carry out a
particular task.
 A method is called by specifying the method and its
arguments.
Analyzing Your First Program: main Method

• Every Java application contains a class with a main


method
– When the application starts, the instructions in the main method are
executed

• Declaring a main method


public static void main(String[] args)
{
...

}
Main Function

• In the Java programming Language, every application must contain


a main method whose signature is:
public static void main(String[] args)

• The modifiers public and static can be written in either order (public
static or static public), but the convention is to use public static.

• The main method is similar to the main function in C and C++, and it
is the entry point for your application.

• The main function accepts a single argument, an array of elements


of type string
Main Function (Cont.)

 This array is the mechanism through which the run


time system passes information to your application
for example:
Java MyApp arg1 arg2

 Each string in the array is called a command-line


argument .
Analyzing Your First Program: Statements

 The body of the main method contains statements.


 Our method has a single statement:
System.out.println("Hello, World!");
 It prints a line of text:
Hello, World!
Analyzing Your First Program: Method Call

 A method call:
System.out.println("Hello, World!");

 A method call requires:


1. The method you want to use (in this case, System.out.println)
2. Any values the method needs to carry out its task enclosed in
parentheses (in this case, "Hello, World!")

 The technical term for such values is arguments


Syntax 1.1 Java Program
Analyzing Your First Program: Strings

• String: a sequence of characters enclosed in double


quotation marks:
"Hello, World!"
Analyzing Your First Program: Printing

• You can print numerical values


System.out.println(3 + 4);
– evaluates the expression 3 + 4
– displays the number 7.

• System.out.println method prints a string or a number and then


starts a new line.
– The sequence of statements
System.out.println("Hello");
System.out.println("World!");
– Prints two lines
Hello
World!
• There is a second method, System.out.print, that you can use to
print an item without starting a new line
Self Check 1.6

• What does the following set of statements print?


System.out.print("My lucky number
is"); System.out.println(3 + 4 + 5);

Answer: The printout is My lucky number is12. It


would be a good idea to add a space after the “is”.
References
 Instructor materials associated to “Big Java: Early
Objects”. By Cay Horstmann. Publisher: Wiley, ISBN
978-1-118-43111-5.
 Previous year slides prepared by Dr. Khalil Abuosba

Copyright © 2014 by John Wiley & Sons. All rights reserved.


54 54

Vous aimerez peut-être aussi