Jimma Institute of Technology
School of Electrical and Computer
Engineering
OOP-Object Oriented Programming
(ECEG-3142)
Fetulhak Abdurahman
afetulhak@[Link]
office no. B-0028
ECEg-3142 JiT
Chapter 1 - 1
Course Overview
Java as a second language course
Teaches programming in oop/Java for people who already know
how to program in C/C++ or similar language
Pre-requisites
Basic programming background (C/C++)
ECEg-3142 JiT
Chapter 1 - 2
Class Structure
Lectures
(GIV) MON (10:00 12:00 a.m.) & wed (3:15-5:00 pm)
(CR2202)
(CR2202)
(GIII) wed (8:00-10:00 am) & Thur (3:15-5:00 pm)
(CR7304)
(CR2202)
Lab hours
For the labs, bring a laptop to class if you have one.
Office hours
Theoretical principles
Programming issues
ECEg-3142 JiT
Chapter 1 - 3
Text Book
Introduction to Object-Oriented Programming using java by
C. Thomas wu
Java is an open language which is very popular on the
Web and so everything you need is available on the Web!
ECEg-3142 JiT
Chapter 1 - 4
Outline
Introduce JAVA
Introduction to OOP Concepts
Classes and Objects
Messages and Methods
Getting started with java
The first java program and its components
Software development lifecycle
ECEg-3142 JiT
Chapter 1 - 5
Chapter 1
Introduction to
Object-Oriented
Programming and
Software
Development
ECEg-3142 JiT
Chapter 1 - 6
Objectives
After you have read and studied this chapter, you
should be able to
Name the basic components of object-oriented programming
Differentiate classes and objects.
Differentiate class and instance methods.
Differentiate class and instance data values.
Draw program diagrams using icons for classes and objects
Describe significance of inheritance in object-oriented programs
Name and explain the stages of the software lifecycle
ECEg-3142 JiT
Chapter 1 - 7
Common errors in programming
for(int i= 0; i< 3; i++)
[Link](hello);
[Link](world);
What will be the output on the screen?
ECEg-3142 JiT
Chapter 1 - 8
Procedural vs. Object-Oriented
Programming
The unit in procedural programming is function, and unit
in object-oriented programming is class
Procedural programming concentrates on creating
functions, while object-oriented programming starts from
isolating the classes, and then look for the methods inside
them.
Procedural programming separates the data of the
program from the operations that manipulate the data,
while object-oriented programming focus on both of them
procedural
ECEg-3142 JiT
object-oriented
ECEg-3142 JiT
Chapter 1 - 10
Advantages of Object-Oriented System
Development
Objects are more natural
Reuse
Classes and objects can be invented once and used
many times during analysis, design, and
programming
Do not need source code for reused class, simply
need to know interface (import)
ECEg-3142 JiT
Chapter 1 - 11
Introducing Java
Released mid 1995 by Sun Microsystems
Designed to be:
A powerful, full-featured, pure OO development
language
Easy to learn - syntax is similar to C++
Platform independent
Support development of applications for networked
environment
Ideal for Web-based applications
ECEg-3142 JiT
Chapter 1 - 12
Introducing Java
Powerful
Class library
Hundreds of prewritten classes
Provide methods to accomplish various tasks
OO
Implements OO concepts (what is that???)
Encourages good software design
Reduces debugging and maintenance
ECEg-3142 JiT
Chapter 1 - 13
Introducing Java
Simplicity
Keywords
Java has 48 keywords
vs. Cobol (>300) or VB which have hundreds
Have special meaning in the language
Used in writing statements
ECEg-3142 JiT
Chapter 1 - 14
Reserved Words
The Java reserved words:
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
ECEg-3142 JiT
Chapter 1 - 15
Program Development
The mechanics of developing a program include
several activities
writing the program in a specific programming language
(such as Java)
translating the program into a form that the computer can
execute
investigating and fixing various types of errors that can occur
Software tools can be used to help with all parts of this
process
ECEg-3142 JiT
Chapter 1 - 16
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
ECEg-3142 JiT
Chapter 1 - 17
Errors
A program can have three 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 errors)
A program may run, but produce incorrect results, perhaps
using an incorrect formula (logical errors)
ECEg-3142 JiT
Chapter 1 - 18
Programming Languages
Each type of CPU executes only a particular
machine language
A program must be translated into machine
language before it can be executed
A compiler is a software tool which translates
source code into a specific target language
Often, that target language is the machine
language for a particular CPU type
ECEg-3142 JiT
The Java approach is somewhat different
Chapter 1 - 19
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
ECEg-3142 JiT
Chapter 1 - 20
Introducing Java
Portability
Programs can be written and compiled once, then run
on different platforms
Important for internet applications (applets)
Achieved by using:
Bytecode
Produced when a Java program is compiled
Interpreter (Java Virtual Machine JVM)
Execution environment for bytecode on each platform
ECEg-3142 JiT
Chapter 1 - 21
ECEg-3142 JiT
Chapter 1 - 22
Introducing Java
Development environments
Java Development Kit
Available free from Sun/oracle Web site
Includes: compiler JVM and prewritten classes
Integrated Development Environments (IDEs)
Provide:
Sophisticated editors
Debugging tools
Graphical development tools
We will use Eclipse IDE
ECEg-3142 JiT
Chapter 1 - 23
Development Environments
There are many programs that support the
development of Java software, including:
Sun Java Development Kit (JDK)
Sun NetBeans
IBM Eclipse
Borland JBuilder
MetroWerks CodeWarrior
BlueJ
jGRASP
Though the details of these environments differ, the
basic compilation and execution process is
essentially the same
ECEg-3142 JiT
Chapter 1 - 24
Building a Java Class
Each source code file defines a class
Class
HelloWorldWideWeb
File
[Link]
ECEg-3142 JiT
Chapter 1 - 25
Building a Java Class
Class header
Describes class contained in source code file
Keywords:
public
Indicates class has public availability
class
Indicates line of code is a class header
ECEg-3142 JiT
Chapter 1 - 26
Building a Java Class
Identifiers
Name of a class, method, or variable
Can be any length
Can include any character except a space
Must begin with a letter of the alphabet, a dollar sign ($), or
the underscore (_) character
Java is case sensitive
Public isnt the same as public
ECEg-3142 JiT
Chapter 1 - 27
Identifiers
Identifiers are the words a programmer uses in a program
An 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 - Loan
upper case for constants - MAXIMUM
ECEg-3142 JiT
Chapter 1 - 28
Java Program Structure GIV
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
ECEg-3142 JiT
Chapter 1 - 29
[Link]
public class Jimmauniversity
{
//----------------------------------------------------------------// Prints motto of jimma university .
//----------------------------------------------------------------public static void main (String[] args)
{
[Link] ("A motto for jimma university");
[Link] ("We are in the community.");
}
}
ECEg-3142 JiT
Chapter 1 - 30
Java Program Structure
//
comments about the class
public class MyProgram
{
class header
class body
Comments can be placed almost anywher
}
ECEg-3142 JiT
Chapter 1 - 31
Java Program Structure
//
comments about the class
public class MyProgram
{
//
comments about the method
public static void main (String[] args)
{
method body
method header
}
}
ECEg-3142 JiT
Chapter 1 - 32
Comments GIII
Comments in a program are called inline
documentation
They 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
*/
*/
ECEg-3142 JiT
Chapter 1 - 33
Building a Java Class
Java code generally consists of:
Comments
Variable definitions
e.g.
int aNumber = 1;
boolean isFound = true;
double anotherNumber = 1.50;
String s = example of a string;
note the naming conventions
Method definitions
e.g.
the main method in applications
public static void main (String[] args) {
}
public void computeTax();
again note the naming conventions
ECEg-3142 JiT
Chapter 1 - 34
Variable Definitions
Variable definitions
Variable: name of place in memory that can contain data
All variables have:
Data type kind of data variable can contain
Name identifier that refers to the variable
Value the default or specified value
also called the literal of the statement
Semicolon
Remember: All java statements end with a semicolon!
e.g.
String s = MC697;
int count = 5;
ECEg-3142 JiT
Chapter 1 - 35
Variable Definitions
Initializing Variables
Assignment operator (=)
Used to assign value to a variable
char c = a; - note the single quotes
boolean b = true;
double d = 1.25;
Important: This is different from the comparative equals (==)
If variable is not initialized, most will default to null.
All variables should be initialized.
ECEg-3142 JiT
Chapter 1 - 36
Data Types
Declaring Variables
Variable data type must be declared prior to initialization
There are two basic data types:
Primitive data types
Eight available primitive data types
Primitive data types are not capitalized in variable declarations
int aNumber = 5;
Reference data types
These data types are capitalized.
String s = example string;
ECEg-3142 JiT
Chapter 1 - 37
ECEg-3142 JiT
Chapter 1 - 38
Data Types
Using Reference Variables
Uses class name as a data type
Points to an instance of that class
Example:
String s = Hello World;
Employee emp1;
ECEg-3142 JiT
Chapter 1 - 39
Variable Constants
Using Constants
Variable with a value that doesnt change
Keyword
final
Denotes value cannot change
Example:
final double SALES_TAX_RATE = 4.5;
note the naming convention
other examples?
ECEg-3142 JiT
Chapter 1 - 40
Method Defnitions
Methods contain:
access modifier
defines who can call this method
return type
defines what this method will return
static
optional - we will discuss this later
method name
should begin with a lower case
argument definition section
defines what input is expected in this method
block of code with statements
ECEg-3142 JiT
Chapter 1 - 41
Statements Within a Method
This is the logic of the program.
Can define and assign variables.
Can invoke another method
Send the method a message asking it to execute
Message is sent in the argument section.
e.g. [Link](output from method);
What is the argument in this method?
ECEg-3142 JiT
Chapter 1 - 42
Computing with Java
Changing Data Types
If changing data type results in no loss of precision,
can be done implicitly:
int c = 5; double a, b = 3.5;
a = b + c;
What is it called when you explicitly change the data
type?
ECEg-3142 JiT
Chapter 1 - 43
Computing with Java
Casting allows data type changes explicitly with loss
of precision:
int a, c = 5; double b = 3.5;
a = (int) b + c;
ECEg-3142 JiT
Chapter 1 - 44
Computing with Java
Operators
Arithmetic operators (+,-,*,/)
addition, subtraction, multiplication, division
Precedence using parentheses
Remainder (modulus) operator (%)
Produces remainder from division of two integers
Concatenation operator (+)
Joins String literals and variables
Automatically converts numeric and Boolean values to strings before use in
println method
Math Class
Methods for exponentiation, rounding, etc.
ECEg-3142 JiT
Chapter 1 - 45
ECEg-3142 JiT
Chapter 1 - 46
Computing with Java
Special Operators
For writing shortcut code
Increment operator (++)
Add one to a variable
Decrement operator (--)
Subtract one from a variable
Assignment operator with arithmetic operators:
total = total + 5;
What is another way of writing this statement?
ECEg-3142 JiT
Chapter 1 - 47
OOP Concepts
ECEg-3142 JiT
Chapter 1 - 48
The first java/oop program
public class HelloWorld{
public static void main(String[] args){
[Link](Hello World!);
}
}
ECEg-3142 JiT
Chapter 1 - 49
What is Object-Orientation about?
One of the key challenges faced by Computer Scientist is how to handle complexity.
Two main concepts used to manage complexity are Modularity and Abstractions.
Modularity means breaking a large system up into smaller pieces until
each piece becomes simple enough to be handled easily.
Abstraction means hiding implementation details in a module and
providing a well-defined interface through which the functionality of the
module can be accessed by other modules. Thus, each module in a
system is treated as a black box by other modules.
Over the years, computer scientists have developed a number of approaches to achieve
modularity and abstraction.
The latest of these approaches is Object-Orientation or OO for short.
The key concept in OO is of course Object, so we need to first understand what an object
is.
ECEg-3142 JiT
Chapter 1 - 50
What is an Object?
An Object is a software entity that models something in the real world. It has two
main properties:
State: the object encapsulates information about itself - fields.
Behaviour: the object can do some things on behalf of other objects methods
Example: In a banking system, a particular bank account is an example of an object.
Its state consists of attributes like: owner, account number, balance, etc.
Its behaviours consist of: deposit(), withdraw(), etc.
Other examples of objects are:
myself an instructor object. What are my fields and methods?
you a student object
this room a room object
this university
your car, etc.
In an OO system, objects are created from something called a Class, so next we
need to know what a class is.
ECEg-3142 JiT
Chapter 1 - 51
What is a class?
A class is a general, abstract representation of an object, that specifies the fields and methods that
such an object has.
When we write OO programs we don't define individual objects, we define classes, and then use
them as templates for constructing objects. Each individual object is called an instance of its class.
For example, you might have a Tree class that describes the features of all trees (each tree has
branches and roots, grows, etc.).
The Tree class serves as an abstract model for the concept of a tree. To reach out and grab, or cut
down a tree, you must have a concrete instance of that tree a tree object.
Of course, once you have a Tree class, you can create lots of different instances of that tree, and
each different tree instance can have different features (it can be short, tall, bushy, have fruits, etc)
ECEg-3142 JiT
Chapter 1 - 52
Class & Objects
CLASS: Furniture
Name
Number
methods: Example
ChangeNumber
Objects:
Desk
123445
ChairA
32143
ChairB
45687
ECEg-3142 JiT
Chapter 1 - 53
Constructing Objects from classes
Once a class has been defined, it can be used to create any number of
objects of that class.
To create an object, we use new operator, the class name, and supply
construction parameters (if any) in parenthesis.
For example, the following statement creates and prints an object of
the Rectangle class
[Link](new Rectangle(5, 10, 20, 30));
An object reference variable is declared by given the class name
followed by the variable as in:
Rectangle myRectangle;
ECEg-3142 JiT
Chapter 1 - 54
Constructing Objects from classes
(cont.)
Once the variable is declared, it can be used to create an object and store its reference in
the variable as follows:
myRectangle = new Rectangle(5, 10, 20, 30);
In fact, the process of declaring an object reference variable and creating an object can
be combined in one statement as follows.
Rectangle myRectangle = new Rectangle(5, 10, 20, 30);
The relationship between the reference variable, myRectangle and the Rectangle object
created is shown in the following figure :
ECEg-3142 JiT
Chapter 1 - 55
Exercise
public class Person {
// fields
String name;
int age;
// one method
void birthday () {
age = age + 1;
[Link](HBD! You are + age +years old now);
}
}
Create/construct an object called john
from the Person class??
ECEg-3142 JiT
Chapter 1 - 56
Examples of Different Object
Types
GUI objects
objects that make up the user interface
e.g. buttons, labels, windows, etc.
Problem Domain objects
Objects that represent a business application
A problem domain is the scope of what the system to be
built will solve. It is the business application.
e.g. An order-entry system
A payroll system
A student system
ECEg-3142 JiT
Chapter 1 - 57
Sample Problem Domain
Company ABC needs to implement an order-entry system
that takes orders from customers for a variety of products.
What are the objects in this problem domain?
Hint: Objects are usually described as nouns.
ECEg-3142 JiT
Chapter 1 - 58
Possible Objects for
this Problem Domain
Customer
Order
Product
ECEg-3142 JiT
Chapter 1 - 59
Classes and Objects
Classes
Define what all objects of the class represent
It is like a blueprint. It describes what the objects
look like
They are a way for programs to model the real
world
Objects
Are the instances of the class
ECEg-3142 JiT
Chapter 1 - 60
Concept: Classes describe objects
Every object belongs to (is an instance of) a class
An object may have fields, or variables
The class describes those fields
An object may have methods
The class describes those methods
A class is like a template/blueprint
You use the classs constructor to make objects
ECEg-3142 JiT
Chapter 1 - 61
Example of a class
public class Employee {
// Fields
public String name;
private double salary;
// Constructor (special type of method)
public Employee(){}
public Employee(String n, double s) {
name = n;
salary = s;
}
// Methods
void pay () {
//is it public or Private???
[Link]("Pay to the order of " +
name + " $" + salary);
}
public String getName() { return name; }
}
ECEg-3142 JiT
Chapter 1 - 62
Concept: Objects must be created
int n; does two things:
It declares that n is an integer variable
It allocates space to hold a value for n
For a primitive, this is all that is needed
Employee secretary; also does two things
It declares that secretary is type Employee
It allocates space to hold a reference to an Employee
For an object, this is not all that is needed
secretary = new Employee ( );
This allocate space to hold a value for the Employee
Until you do this, the Employee is null
ECEg-3142 JiT
Chapter 1 - 63
Notation: How to declare and create
objects
Employee secretary; // declares secretary
secretary = new Employee (); // allocates space
Employee secretary = new Employee(); // does both
But the secretary is still "blank"
[Link] = "Adele"; // dot notation
secretary. salary = 230.0;
[Link] (); // sends a message
[Link] ();
ECEg-3142 JiT
Chapter 1 - 64
Graphical Representation of a Class
<Class Name>
Example:
Account
We
Weuse
useaarectangle
rectangleto
to
represent
a
class
with
represent a class with
its
itsname
nameappearing
appearing
inside
the
inside therectangle.
rectangle.
Motorcycle
The notation we used here is based on the industry standard notation
called UML, which stands for Unified Modeling Language.
ECEg-3142 JiT
Chapter 1 - 65
Graphical Representation of an Object
<Object Name>
We
Weuse
useaarectangle
rectangleto
to
represent
an
object
and
represent an object and
place
placethe
theunderlined
underlined
name
of
the
name of theobject
objectinside
inside
the
rectangle.
the rectangle.
Example:
SV198
This
Thisisisan
anobject
objectnamed
named
SV198.
SV198.
ECEg-3142 JiT
Chapter 1 - 66
An Object with the Class Name
<Object Name> : <Class Name>
This
Thisnotation
notationindicates
indicates
the
class
which
the class whichthe
the
object
is
an
instance.
object is an instance.
Example:
SV198 : BankAccount
This
Thistells
tellsan
anobject
object
SV198
is
an
instance
SV198 is an instanceof
of
the
BankAccount
class.
the BankAccount class.
ECEg-3142 JiT
Chapter 1 - 67
ECEg-3142 JiT
68
Object Attributes and Methods
Classes contain two things:
Fields (attributes, data members, class variables):
Data items that differentiate one object of the class from another. e.g.
employee name, student number
Characteristics of an object that have values
What are some possible attributes for the customer object?
Methods (behaviors):
Named, self-contained blocks of code that typically operate on the fields
Describe what an object can do
Can be thought of as the verbs in a problem domain
What are some possible methods for the customer object?
ECEg-3142 JiT
Chapter 1 - 69
Fields
field: A variable inside an object that is part of its
state.
Each object has its own copy of each field.
Declaration syntax:
private type name;
Example:
public class Point {
private int x;
private int y;
...
}
ECEg-3142 JiT
Chapter 1 - 70
public class Point {
//fields
private int x;
private int y;
//methods
public void setPoint(int xpos, int ypos)
{
//two objects from Point class
Point p1=new Point();
Point p2= new Point();
[Link](20,30);
[Link](5,10);
x= xpos;
y= ypos;
}
ECEg-3142 JiT
[Link](value of x for object P1 is +
P1.x); ??? what is the solution?
Chapter 1 - 71
ECEg-3142 JiT
Chapter 1 - 72
ECEg-3142 JiT
Chapter 1 - 73
Object Interactions and Messages
Objects interact with other objects in a variety of relationships
e.g. one-to-one, one-to-many
Messages
The means by which objects interact
Example:
User initiates interaction via messages to GUI objects
GUI objects interact with problem domain objects via messages
Problem domain objects interact with each other and GUI objects via
messages
GUI objects respond to user via messages
ECEg-3142 JiT
Chapter 1 - 74
ECEg-3142 JiT
Chapter 1 - 75
Messages and Methods
To instruct a class or an object to perform a task, we
send a message to it.
You can send a message only to the classes and
objects that understand the message you sent to
them.
A class or an object must possess a matching method
to be able to handle the received message.
A method defined for a class is called a class method,
and a method defined for an object is called an
instance method.
A value we pass to an object when sending a
message is called an argument of the message.
ECEg-3142 JiT
Chapter 1 - 76
Instance methods
instance method (or object method): Exists inside
each object of a class and gives behavior to each object.
public type name(parameters) {
statements;
}
same syntax as static methods, but without static keyword
Example:
public void tranlate(int dx, int dy) {
x += dx;
y += dy;
}
ECEg-3142 JiT
Chapter 1 - 77
Categories of methods
accessor:
object state.
A method that lets clients examine
Examples: distance, distanceFromOrigin
often has a non-void return type
mutator: A method that modifies an object's state.
Examples: setLocation, translate
helper: Assists some other method in performing its
task.
often declared as private so outside clients cannot call it
ECEg-3142 JiT
Chapter 1 - 78
Message / Receiver
Objects are manipulated by sending them
messages
The object itself is therefore a receiver of messages
The message is usually a method invocation
Example:
String name = jhon java;
[Link]();
// name is receiver, reverse is the message
ECEg-3142 JiT
Chapter 1 - 79
Sending a Message
Message
Messagedeposit
depositwith
with
the
argument
250.00
the argument 250.00isis
sent
sentto
toaaBankAccount
BankAccount
object
SV198.
object SV198.
deposit 250.00
SV198 : BankAccount
ECEg-3142 JiT
Chapter 1 - 80
Sending a Message and Getting an Answer
Ask
Askfor
forthe
thecurrent
current
balance
of
this
balance of this
particular
particularaccount.
account.
getCurrentBalance()
SV198 : BankAccount
current balance
The
Thecurrent
currentbalance
balanceof
of
SV198
is
returned.
SV198 is returned.
ECEg-3142 JiT
Chapter 1 - 81
Calling a Class Method
Ask
Askfor
forthe
themaximum
maximum
possible
speed
possible speedfor
forall
all
MobileRobot
objects
MobileRobot objectsisis
returned.
returned.
MobileRobot
getMaximumSpeed()
maximum speed
ECEg-3142 JiT
Chapter 1 - 82
Class and Instance Data Values
An object is comprised of data values and methods.
An instance data value is used to maintain information
specific to individual instances. For example, each
BankAccount object maintains its balance.
A class data value is used to maintain information shared
by all instances or aggregate information about the
instances.
For example, minimum balance is the information shared
by all Account objects, whereas the average balance of all
BankAccount objects is an aggregate information.
ECEg-3142 JiT
Chapter 1 - 83
Sample Instance Data Value
SV129 : BankAccount
SV098 : BankAccount
SV211 : BankAccount
current balance
908.55
current balance
1304.98
current balance
All
Allthree
threeBankAccount
BankAccount
objects
possess
objects possessthe
the
same
instance
data
same instance data
value
valuecurrent
currentbalance.
balance.
354.00
The
Theactual
actualdollar
dollar
amounts
are,
amounts are,of
ofcourse,
course,
different.
different.
ECEg-3142 JiT
Chapter 1 - 84
Sample Class Data Value
BankAccount
minimum balance
100.00
There
Thereisisone
onecopy
copyofof
minimum
minimumbalance
balancefor
for
the
whole
class
and
the whole class and
shared
sharedby
byall
allinstances.
instances.
This
Thisline
lineisisan
an
instance-of
instance-of
relationship.
relationship.
SV129 : BankAccount
SV098 : BankAccount
SV211 : BankAccount
current balance
908.55
current balance
1304.98
current balance
354.00
ECEg-3142 JiT
Chapter 1 - 85
Object Icon with Class Data Value
SV129 : BankAccount
minimum balance
100.00
current balance
908.55
When
Whenthe
theclass
classicon
iconisis
not
notshown,
shown,we
weinclude
include
the
class
data
value
the class data valueinin
the
theobject
objecticon
iconitself.
itself.
ECEg-3142 JiT
Chapter 1 - 86
Encapsulation and Information Hiding
Encapsulation
Objects have attributes and methods combined into one unit
Information Hiding
Hiding the internal structure of objects, protecting them from
corruption
Identity
Unique reference for each object
Persistent objects
Defined as available for use over time
ECEg-3142 JiT
Chapter 1 - 87
Inheritance
Inheritance is a mechanism in OOP to design two
or more entities that are different but share many
common features.
Features common to all classes are defined in the
superclass.
The classes that inherit common features from the
superclass are called subclasses.
We also call the superclass an ancestor and the subclass a
descendant.
ECEg-3142 JiT
Chapter 1 - 88
Inheritance
inheritance: Forming new classes based on existing
ones.
a way to share/reuse code between two or more classes
superclass: Parent class being extended.
subclass: Child class that inherits behavior from superclass.
gets a copy of every field and method from superclass
is-a relationship: Each object of the subclass also "is a(n)"
object of the superclass and can be treated as one.
ECEg-3142 JiT
Chapter 1 - 89
Inheritance syntax
public class name extends superclass {
Example:
public class Lawyer extends Employee {
...
}
By extending Employee, each Lawyer object now:
receives a copy of each method from Employee
automatically
can be treated as an Employee by client code
Lawyer can also replace ("override") behavior from
Employee.
ECEg-3142 JiT
Chapter 1 90
A Sample Inheritance
Here are the superclass Account and its
subclasses Savings and Checking.
Account
Checking
Savings
ECEg-3142 JiT
Chapter 1 - 91
Inheritance Hierarchy
An example of inheritance hierarchy among
different types of students.
Student
Graduate
Masters
Doctoral
Undergrad
Law
Commuting
Resident
ECEg-3142 JiT
Chapter 1 - 92
Concept: Classes form a hierarchy
Classes are arranged in a treelike structure called a
hierarchy
The class at the root is named Object
Every class, except Object, has a superclass
A class may have several ancestors, up to Object
When you define a class, you specify its superclass
If you dont specify a superclass, Object is assumed
Every class may have one or more subclasses
ECEg-3142 JiT
Chapter 1 - 93
Example of (part of) a hierarchy
Container
Panel
ScrollPane
Window
Dialog
Frame
FileDialog
A FileDialog is a Dialog is a Window is a Container
ECEg-3142 JiT
Chapter 1 - 94
Concept: Objects inherit from
superclasses
A class describes fields and methods
Objects of that class have those fields and
methods
But an object also inherits:
the fields described in the class's superclasses
the methods described in the class's superclasses
A class is not a complete description of its
objects!
ECEg-3142 JiT
Chapter 1 - 95
Example of inheritance
class Person {
String name;
int age;
void birthday () {
age = age + 1;
}
}
class Employee
extends Person {
double salary;
void pay () { ...}
}
Every Employee has name and age fields and
birthday method as well as a salary field and a pay
method.
ECEg-3142 JiT
Chapter 1 - 96
Concept: A variable can hold subclass
objects
Suppose B is a subclass of A
A objects can be assigned to A variables
B objects can be assigned to B variables
B objects can be assigned to A variables, but
A objects can not be assigned to B variables
Every B is also an A but not every A is a B
You can cast: bVariable = (B) aObject;
In this case, Java does a runtime check
ECEg-3142 JiT
Chapter 1 - 97
Example: Assignment of subclasses
class JU { ... }
class Jit extends JU { ... }
JU myJu;
JU campus1 = new JU ();
Jit yourcampus;
Jit kito = new Jit();
myJu = campus1;
yourcampus = kito;
myJu = kito;
yourcampus = campus1;
yourcampus = (Jit) campus1;
// ok
// ok
//ok
// illegal
//runtime check
ECEg-3142 JiT
Chapter 1 - 98
Concept: Methods can be overridden
class Bird extends Animal {
void fly (String destination) {
location = destination;
}
}
class Penguin extends Bird {
void fly (String whatever) { }
}
So birds can fly. Except penguins.
ECEg-3142 JiT
Chapter 1 - 99
Concept: Don't call functions, send
messages
Bird someBird = pingu;
[Link] (jimma");
Did pingu actually go anywhere?
You sent the message fly(...) to pingu
If pingu is a penguin, he ignored it
Otherwise he used the method defined in Bird
You did not directly call any method
ECEg-3142 JiT
You cannot tell, without studying the program, which
method actually gets used
The same statement may result in different methods
being used at different times
Chapter 1 - 100
Software Engineering
Much like building a skyscraper, we need a
disciplined approach in developing complex
software applications.
Software engineering is the application of a
systematic and disciplined approach to the
development, testing, and maintenance of a
program.
In this class, we will learn how to apply sound
software engineering principles when we develop
sample programs.
ECEg-3142 JiT
Chapter 1 - 101
Software Life Cycle
The sequence of stages from conception to
operation of a program is called software life
cycle.
Five stages are
Analysis
Design
Coding
Testing
Operation and Maintenance
ECEg-3142 JiT
Chapter 1 - 102