0% found this document useful (0 votes)
6 views

Unit_1_-_Introduction

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit_1_-_Introduction

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

2/2/2009

Unit 1 – Introduction
Faculty of Computer Science 2009
Universitas Indonesia

 This course teaches the fundamental


ideas behind the object-oriented
approach to programming; through the
widely-used Java programming language.
 This course concentrates on those aspects
of the Java language that best
demonstrate object-oriented principles
and good practice.
 This course also teaches students how to
describe and communicate their object-
oriented design.
Course Objectives

1
2/2/2009

 Deitel (2006), JAVA How to Program, 7th


ed, Pearson Education, Inc., New Jersey,
USA.
 Bruce Eckel, Thinking in Java 4th ed,
Prentice Hall / Pearson Education. 2006
ISBN 0-13-187248-6

References

 James Gosling, Bill Joy, Guy Steele, Gilad


Bracha, The Java Language Specification
3rd ed, Sun Microsystem 2005.
 Michael Kölling, The BlueJ Tutorial /
Manual version 2.
 David J. Barnes & Michael Kölling, Objects
First with Java: A Practical Introduction
using BlueJ Third Edition, Prentice Hall /
Pearson Education, 2006ISBN 0-13-197-
629X (currently unavailable in faculty
library)
Other Books

2
2/2/2009

 BlueJ version 2.1, downloadable from


www.bluej.org (old version is currently
available in Faculty laboratory)
 JDK 5 (including JRE 5), Sun Microsystem,
downloadable from java.sun.com (Latest
version is currently available in Faculty
Laboratory)

Software / Tool

 Four (4) quizes


 Two (2) individual programming
assignments
 Two (2) pair programming assignments
 One (1) Team assignment (group of 5-7)

Assignments

3
2/2/2009

 1.5 hours perweek starting next week.


 One tutor for 15-20 students.
 Schedule:
 Obligatory !
 During the tutorial, students are expected
to do and submit the given exercise
(worksheet)

Lab Activities

 Mid Exam 20%


 Programming Exam 20%
 Final Exam 25%
 Assignments 20%
 Quizzes 15%

Grading Scheme

4
2/2/2009

◦ Please ask questions and give feedback.


◦ If you really feel that I am going toooooooo
fast, please, interrupt me!
◦ There is no point in giving classes if nobody
understands me.

During the Courses

 A program is a set of instructions to a


computer.
 These instructions are written in a
programming language.
 Each computer understands one language, its
machine language, which is not
human−readable.
 A program is written in a high level language
(for humans) & then translated into machine
code (for the computer).
 The purpose of your studying this unit is to
write well structured, robust,
maintainable software − not just to write
code that simply works!

Software

5
2/2/2009

 Suppose I wish to send flowers to a


friend, Sally, who lives in a city
many miles away.

◦ What should I do?

Illustration of OOP Concepts :


Sending Flowers to a Friend

 Solution: Find an appropriate agent,


namely Flora, and pass to her a message
containing my request
◦ It is the responsibility of Flora to satisfy my
request
◦ There is some method – some algorithm or
some set of operations – used to satisfy my
request
 This information, i.e., details, is usually hidden from
my inspection.

Agents and Communities

6
2/2/2009

The community of agents helping


me

 An object-oriented program is
structured as a community of
interacting agents, called objects.
◦ Each object has a role to play.
◦ Each object provides a service, or
performs an action, that is used by other
members of the community.

An Observation

7
2/2/2009

◦ Action is initiated in OOP by the


transmission of a message to an agent
(an object) responsible for the action.
 The message encodes the request for an action
and is accompanied by any additional
information (arguments) needed to carry out
the request.
◦ The receiver is the object to whom the
message is sent. If the receiver accepts
the message, it accepts the responsibility
to carry out the indicated action.
 In response to a message, the receiver will
perform some method to satisfy the request.
Messages and Methods

 The client sending the request need


not know the actual means by which
the request will be honored.

 An important part of the OOP is the


development of reusable
components
◦ “thrusting” others

Information Hiding Principles

8
2/2/2009

◦ PC: there is no designated receiver


◦ MP: Interpretation of the message is
dependent on the receiver and can vary with
different receivers

◦ Usually, the specific receiver for any given


message will not be known until run time, so
the determination of which method to invoke
cannot be made until then.
 late binding – between a message and the code
fragment (method) used to respond to the
message.
 vs. compile-time or link-time binding in PC.

Message Passing vs Procedure


Calling

 Describe behavior in terms of


responsibilities
◦ increases level of abstraction
◦ greater independence between objects, a
critical factor in solving complex problems
◦ Protocol: The entire collection of
responsibilities associated with an object

Responsibilities

9
2/2/2009

 “Asknot what you can do to your


data structures, but what your data
structures can do for you”

◦ We can use the term Florist to represent


the category (or class) of all florists.
 I am able to make certain assumptions
because I have information about florists in
general, and I expect that Flora, being an
instance of this category, will fit the general
pattern.
◦ All objects are instances of a class
◦ The method invoked by an object in
response to a message is determined by
the class of the receiver
◦ All objects of a given class use the same
method in response to similar messages.

Classes and Instances

10
2/2/2009

•Ihave more information


about Flora – not
necessarily because she is
a florist but because she is
a shopkeeper.
•One way to think about
how I have organized my
knowledge of Flora is in
terms of a hierarchy of
categories:

Class Hierarchies - Inheritance

•More abstract classes


are listed near the top
of the tree
•More specific classes
and individuals are
listed near the
bottom.

A class hierarchy of various


material objects

11
2/2/2009

◦ The principle that knowledge of a more general


category is also applicable to a more specific
category is called inheritance.
 The class Florist will inherit attributes of the class (or
category) Shopkeeper.
◦ Classes can be organized into a hierarchical
inheritance structure.
 A child class (or subclass) will inherit attributes from a
parent class higher in the hierarchy. An abstract parent
class is a class for which there are no direct instances;
it is used only to create subclasses.

◦ That Liz and my florist Flora will respond to my


message by different methods is an example of
one form of Polymorphism.
◦ That I do not, need not, know exactly what
method Flora will use to honor my message is
an example of information hiding.

12
2/2/2009

◦ Almost all major concepts of OOP, such as


objects, classes, and inheritance hierarchies,
were developed in the 1960s
 Simula language, by Norwegian Computing
Center
◦ In the 1970s, Alan Kay developed Smalltalk
language at Xerox PARC (the Palo Alto
Research Center)
 targeted to be understandable to people with
no prior training in computer use
 demonstrated by experiments conducted using
children as programmers
History of Object-Oriented
Programming Languages

◦ Bjarne Stroustrup at Bell Labs who had


learned Simula during his Ph.D. studies
developed C++ as an extension of C

◦ Later many other OOP languages were


developed: Eiffel, Objective-C, Actor,
Object Pascal, etc.

◦ Since 1986 (first OOPSLA conference)


OOP is a mainstream player in the PL
domain the rather than a revolutionary
one.

13
2/2/2009

 We will explore the OOP in the


context of Java programming
language.
◦ OOP has been a hot topic for over a
decade
◦ Java has recently become the commonly
perceived embodiment of object-
oriented ideas

Why Java?

 Javais a general purpose


programming language that can be
used to create almost any type of
computer program.

◦ Especially, it can be used to create


programs intended for execution across
the Internet.

Java Programming Language

14
2/2/2009

◦ It was named Oak in 1991 at Sun


Microsystems.
◦ A computer scientist, James Gosling,
developed Oak for use in embedded
consumer electronic applications, such as
VCRs.
 This development purpose has determined
many of the characteristics of the language.
 Size and reliability are key features.
◦ The processors that run in embedded systems are very
small and has very little memory. A program must be able
to be translated into a very concise encoding.
◦ Embedded systems should almost never fail.

The History of Java

◦ Java has these features.


 Pointers and goto statement were
eliminated.
 Exception-handling is enforced to handle the
unexpected in a graceful fashion

◦ Unfortunately, Java (or Oak) as a language for


embedded consumer electronics did not
materialize at that time!

15
2/2/2009

◦ Then used for creating Web pages with


dynamic content
◦ Now also used to:
 Develop large-scale enterprise applications, Java
2 platform Enterprise Edition (J2EE)
 Enhance WWW server functionality
 Provide applications for consumer devices (cell
phones, etc.), Java 2 Platform Micro Edition
(J2ME)

 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
 Bytecode Verifier confirms bytecodes do not
violate security restrictions
◦ Execute
 JVM translates bytecodes into machine language

Typical Java Development


Environment

16
2/2/2009

Typical Java
development
environment.

 Platform independence is achieved by running byte


code on a Java virtual machine (jvm)
 Byte code is a machine code for the jvm. A java
compiler compiles from source code to byte code
 Each machine actually needs code in its own
particular native machine language: thus byte code
needs to be interpreted to be able to execute locally
 The overheads of interpreting byte code are lower
than traditional intepreters because the conversion is
from machine code (jvm) to machine code (native
machine code). No syntax checking is required
 Java virtual machine is itself a program whose job it
is to interpret the Java byte code e.g. aplets are small
Java programs that are run on a jvm incorporated in
a web browser

Platform Independence

17
2/2/2009

 Good:
◦ Platform independent execution
◦ Platform independent binary data (files etc)
◦ Robust
◦ Does not allow operator overloading. Some
people regard this as a limitation. Others think
operator overloading is not a good idea
anyway!
◦ Comes with a huge class library which allow:
 File input / output
 Graphics
 Event trapping / handling
 3D modelling

Java: Good and Bad

 Bad:
◦ Syntax is adopted from C. This means that
some control structures are primitive and
unstructured
◦ Graphics library still provides problems across
different platforms

Java: Good and Bad

18
2/2/2009

 Alan Kay summarized five basic


characteristics of Smalltalk, the first
successful object-oriented language and
one of the languages upon which Java is
based. These characteristics represent a
pure approach to object-oriented
programming.

OO Characteristics

◦ Everything is an object.
◦ A program is a bunch of objects telling
each other what to do by sending
messages.
◦ Each object has its own memory made
up of other objects.
◦ Every object has a type.
◦ All objects of a particular type can
receive the same messages.

OO Characteristics

19
2/2/2009

◦ Everything is an object.
 Think of an object as a fancy variable;
it stores data, but you can “make
requests” to that object, asking it to
perform operations on itself. In theory,
you can take any conceptual
component in the problem you’re
trying to solve (dogs, buildings,
services, etc.) and represent it as an
object in your program.

 A program is a bunch of objects telling


each other what to do by sending
messages.
◦ To make a request of an object, you “send a
message” to that object. More concretely, you
can think of a message as a request to call a
method that belongs to a particular object.
 Each object has its own memory made
up of other objects.
◦ Put another way, you create a new kind of
object by making a package containing existing
objects. Thus, you can build complexity into a
program while hiding it behind the simplicity of
objects.

20
2/2/2009

 Every object has a type.


◦ Using the parlance, each object is an instance of a
class, in which “class” is synonymous with “type.”
The most important distinguishing characteristic of
a class is: “What messages can you send to it?”
 All objects of a particular type can receive
the same messages.
◦ This is actually a loaded statement, as you will see
later. Because an object of type “circle” is also an
object of type “shape,” a circle is guaranteed to
accept shape messages. This means you can write
code that talks to shapes and automatically handle
anything that fits the description of a shape. This
substitutability is one of the powerful concepts in
OOP.

 There are two basic paradigms for designing


algorithms:
 Non Object Oriented:
◦ Focus is on the steps required to perform the task.
◦ The design of the steps lead to the types of data
structures that will be required.
 Object Oriented:
◦ Focus is on the entities required. i.e. what are the things
that need to be represented in the algorithm and:
 what functionality will each thing require.
 how these things will communicate with each other.
◦ Each entity will be represented as an object.
◦ The design of each object leads to the steps required.
 In this course we will be looking at the Object
Oriented approach.
 The non Object Oriented approach had been
discussed in DDP (Dasar-Dasar Pemrograman)

To be OO or not to be OO?

21
2/2/2009

1 // Fig. 2.1: Welcome1.java

Welcome1.java
2 // Text-printing program.

3

4 public class Welcome1

5 {

6 // main method begins execution of Java application

7 public static void main( String args[] )

8 {

9 System.out.println( "Welcome to Java Programming!" );

10

11 } // end method main

12

13 } // end clazss Welcome1

Welcome to Java Programming!

Small Program Example

 The Java code on the previous slide is entered


into a text file using a text editor
 The name of the .java file MUST be EXACTLY
the same as the name of the class (ie.
Welcome1.java)
 The .java file is then compiled into byte code:
◦ The command would be: javac Welcome1.java
◦ If the program contained errors then error
messages are displayed
◦ Otherwise the byte code is produced
 The byte code is stored in a file called
Welcome1.class
 The program can then be executed using the
command:
◦ java Welcome1
Creating, Compiling, and Running a Java Program

22
2/2/2009

 A Java program starts by executing the


main() method
 The main() method provides the starting
point for the program
 Within the main() method:
◦ Other methods will be invoked
◦ Objects will be created and
◦ Methods within those objects invoked

The main() Method

class SimpleApplication{
String text;

//Constructor
SimpleApplication(){
this.setText("I'm a Simple Program");
}

//Accessor method
String getText(){ return text; }

//Mutator method
void setText(String text){ this.text = text; }

public static void main(String[] args){


SimpleApplication progInst
= new SimpleApplication();
String retrievedText = progInst.getText();
System.out.println(retrievedText);
}
}

Simple Application

23
2/2/2009

Application Structure and


Elements

◦ Classes have a special method called a


constructor that is called when a class instance
is created.
◦ The class constructor always has the same
name as the class and no return type.
◦ If you do not write your own constructor, the
compiler adds an empty constructor, which
calls the no-arguments constructor of its
parent class.
◦ The empty constructor is called the default
constructor.
◦ The default constructor initializes all non-
initialized fields and variables to zero.

Constructors

24
2/2/2009

returnType methodName( /* Argument list */ ) { /* Method body */ }


 A method consists of
◦ A header
◦ A body
 The header consists of
◦ The type of the method
◦ The name of the method
◦ The parameters to the method
 The body consists of a sequence of Java
statements encapsulated by { and }

Introduction to Methods

 A method can be called only for an object,


and that object must be able to perform
that method call.
 Call a method:
objectName.methodName(arg1, arg2, arg3);
 The act of calling a method is commonly
referred to as sending a message to an
object boolean flag() { return true; }
float naturalLogBase() { return 2.718f; }
void nothing() { return; }
void nothing2() {}

Methods

25
2/2/2009

 Field / data member


◦ an object of any type that you can communicate
with via its reference
◦ you must initialize that reference to connect it to an
actual object
 Each object keeps its own storage for its
fields class DataOnly {
int i;
float f;
boolean b;
}
 Class doesn’t do anything, but you can create
an object
DataOnly d = new DataOnly();

Fields

 Refer to a member of an object:


objectReference.member

 Example:

d.i = 47;
d.f = 1.1f; // ‘f’ after number indicates float constant
d.b = false;

Fields

26
2/2/2009

mport javax.swing.*;
import java.awt.*;

public class HelloWorld extends JPanel {

public void paint(Graphics g) {


g.drawString("Hello World!!", 20, 50);
}

public static void main(String[] args) {


JFrame myFrame = new JFrame();
myFrame.add(new HelloWorld());
myFrame.setSize(300,300);
myFrame.setVisible(true);
}
}

Simple HelloWorld!

Applet

27
2/2/2009

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;

public class SimpleApplet extends Applet{

String text = "I'm a simple applet";

public void init() {


text = "I'm a simple applet";
setBackground(Color.cyan);
}

Applet (Sample Code)

public void start() {


System.out.println("starting...");
}

public void stop() {


System.out.println("stopping...");
}

public void destroy() {


System.out.println("preparing to unload...");
}
public void paint(Graphics g){
System.out.println("Paint");
g.setColor(Color.blue);
g.drawRect(0, 0,
getSize().width -1,
getSize().height -1);
g.setColor(Color.red);
g.drawString(text, 15, 25);
}
}

28
2/2/2009

◦ To see the applet in action, you need an HTML


file with the Applet tag as follows:

◦ <HTML>
◦ <BODY>
◦ <APPLET CODE=SimpleApplet.class
WIDTH=200 HEIGHT=100>
◦ </APPLET>
◦ </BODY>
◦ </HTML>

Run the Applet

◦ The Java API Applet class provides what


you need to design the appearance and
manage the behavior of an applet.
◦ This class provides a graphical user
interface (GUI) component called a
Panel and a number of methods.
◦ To create an applet, you extend (or
subclass) the Applet class and
implement the appearance and
behavior you want.

Applet Structure and Elements

29
2/2/2009

◦ The applet's appearance is created


by drawing onto the Panel or by
attaching other GUI components
such as push buttons, scrollbars,
or text areas to the Panel.
◦ The applet's behavior is defined by
implementing the methods.

 Most classes of any complexity extend other


classes.
 To extend another class means to write a new
class that can use the fields and methods defined
in the class being extended.
 The class being extended is the parent class, and
the class doing the extending is the child class.
Another way to say this is the child class inherits
the fields and methods of its parent or chain of
parents.
 Child classes either call or override inherited
methods. This is called single inheritance.

Applet : Extending a class

30
2/2/2009

 The SimpleApplet
class extends Applet
class, which extends
the Panel class,
which extends the
Container class. The
Container class
extends Object,
which is the parent
of all Java API
classes.
Applet : Extending a Class

 The Applet class provides the init, start, stop,


destroy, and paint methods you saw in the
example applet. The SimpleApplet class overrides
these methods to do what the SimpleApplet class
needs them to do. The Applet class provides no
functionality for these methods.
 However, the Applet class does provide
functionality for the setBackground
method,which is called in the init method. The
call to setBackground is an example of calling a
method inherited from a parent class in contrast
to overriding a method inherited from a parent
class.
SimpleApplet

31
2/2/2009

 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

Object Oriented Technology

 Object-Oriented Analysis and Design


(OOA/D)
◦ Essential for large programs
◦ Analyze program requirements, then
develop solution
◦ UML
 Unified Modeling Language

Object Oriented Technology

32
2/2/2009

 History of the UML


◦ Need developed for process with which
to approach OOA/D
◦ Brainchild of Booch, Rumbaugh and
Jacobson
◦ Object Management Group (OMG)
supervised
◦ Version 1.5 is current version
 Version 2 under development

UML

 Graphical representation scheme


 Enables developers to model object-
oriented systems
 Flexible and extensible

UML

33

You might also like