CSC 233 Lecture Slides
CSC 233 Lecture Slides
Object-Oriented Programming
3 Credits
People,books,dogs,cats,cars,airplanes,trains,etc.
Thus,
A class I a blueprint for the creation of objects
Principles of OOP
Abstraction
Encapsulation and information hiding
Inheritance
Polymorphism
OOP vs Structured Programming
Object-oriented Procedural
Bottom-up approach Top-down approach
Divide into objects Divide into functions
Objects communicate Data can be passed from
through methods one function to another
https://www.oracle.com/technetwork/java/javase/downloads/index.html
Accept license agreement and click on the product that fits your machine to
download
Always start your identifiers with letter, seldom use $ or _ to start your identifiers
Use full words instead of cryptic; to enhances understandability
Use camelCase: In Identifiers with more than one word, start other words with uppercase letters
except the first word
Data Types: Primitive and Composite (Array, Class)
Primitive data types
Data Type Description
byte 8-bit signed 2s complement integer ranging from -128 to 127 (inclusive)
short 0
int 0
long 0L
float 0.0f
double 0.0d
boolean false
char ‘\u000’
Literals
Literals Default values
Arithmetic expression
Assignment expression
Logical expression
Relational expression
Operators
Arithmetic operators
Assignment operators
Logical operators
Relational operators
Unary operators
Ternary operator
Operators
Arithmetic operators
Operator Description
+ Additive operator (also used for String
concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Operators
Assignment operators
Operator Description
= x=y
+= x+=y
x=x+y
-= x-=y
x=x-y
*= x*=y
x=x*y
/= x/=y
x=x/y
%= x%=y
x=x%y
Operators
Relational operators
Operator Description
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Is equal to
!= Is not equal to
Operators
Logical operators
Operator Description
&& AND operator Returns true iff both operands are
true
|| Returns true if one or both operands are true
! Inverts the value of a Boolean
& Bitwise AND operator
| Bitwise OR operator
Operators
Unary operators
Operator Description
+ Indicates positive numbers
- Indicates a negative number or expression
++ Increment
-- Decrement
Statement
A Statement is a complete program construct that causes
execution.
Simple statement
Compound statement
Control statement
Statement
Null
statement: is simply nothing terminated with a
semicolon i.e.,
;
Simple statement; is single line statement e.g.
y = s + 15;
Compound statement: is one or more simple statements
Selection statements
If
If-else
else if
Switch
for
foreach
Selection statement
If statement
if (expr) stmt
e.g.
if(age >=18) status = “Adult”;
If-else statement
If(expr) stmt_1
else stmt_2
e.g.
if(age>=18) status = “Adult”;
else status=“Teenager”;
switch statement - byte, short, char, and int
Enum, String, Character, Byte, Short Integer,
switch(expr){
case val_1: stmt_1
break;
case val_2: stmt_2
break;
.
.
.
case val_n: stmt_n
break;
[default: default_stmt]
}
E.g.
int weekDay =5;
switch(weekDay){
case 1: System.out.println(“Sunday”);
break;
case 2: System.out.println(“Monday”);
break;
case 3: System.out.println(“Tuesday”);
break;
case 4: System.out.println(“Wednesday”);
break;
case 5: System.out.println(“Thursday”);
break;
case 6: System.out.println(“Friday”);
break;
case 7: System.out.println(“Saturday”);
break;
default: System.out.println(“Wrong day number”);
}
Iteration statement
while
while(expr)
stmt
e.g.
Short i=1;
While(i<6){
System.out.println(“This is iteration “ +i);
i=i+1;
}
Iteration statement
do - while
do{
stmts
}while(expr);
e.g.
int i=1;
do{
System.out.println(“This is iteration “, i);
i=i+1;
}While(i<6);
Iteration statement
For
for([initialization];[condition];[incr/decr]){ statement(s)
}
e.g.
for(short i=1;i<6;i++)
System.out.println(“This is iteration “, i);
X
index 0 1 2 3 4 5 6 7 8 9
Each component of the array can be referenced through the index as follows: arrayName[n-1]
e.g. X[5]
12 5 34 66 98 65 99 72 45 87
Array
Linear Array
Array declaration
Datatype[] arrayName;
e.g.
int[] x //declare an array of integers
X null
Array allocation
arrayName = new Datatype[size];
e.g.
X = new int[10] //allocates memory for 10 int
X 0 1 2 3 4 5 6 7 8 9
Array
Linear Array
Initializing Array
Datatype[] arrayName = {val1, val2,…valN};
e.g.
int[] x = {23, 7, 90, 76, 12};
Declaration
Datatype[][] arrayName; 34
e.g.
int[][] x Null
X
Array allocation
arrayName = new Datatype[size1][size2];
e.g.
X = new int[2][2]; X
Array
Multi-dimensional Array e.g. matrice
Initialization
double[][] y = {{12.0,7.1},{5.0,13}};
12.0 7.1
5.0 13
y
c
12 5 99 6 233
arrayCopy(…) and copyOf(…)
arraycopy(…) is defined in the class System and has four parameters
43
System.arrayCopy(src, src_position, dest,8dest_position);
34 809 45
copyOf(…) is defined in the class Arrays, it returns array of the same type as its parameter. It as the forms:
Arrays.copyOf(src, len) or
Arrays.copyOfRange(src, src_position, src_end)
Array
Operations on Array
Other operations on Arrays are
sort( )
Arrays.sort(x);
binarySearch(…)
Arrays.binarySearch(array, element);
equals(…)
Arrays.equals(arrayA, arrayB);
Packages
Packages are directories (folders)
Each class belongs to a package
A class is added to a package by using the package statement:
package packageName;
The package statement must precede every other statement in a class i.e. the package statement is the first line of statement in a class
Where the statement is NOT specified, Java places the class in default package
Classes in the same packages serve a similar purpose
java.lang package which contains classes String, System, etc.
java.io, java.net, java.text, java.awt, java.awt.color
Visit: http://java.sun.com/javase/6/docs/api
Why Packages?
Combine/group class that perform similar functionality
Separate classes with similar name
Enhances collaborative software development
Java Classes
Classes are constructs that define objects of the same type.
(Building plan of similar objects)
A Java class uses variables/constants to define data fields and
methods (member functions) to define behaviors.
Java class definition
method_definition
}
where Access types: public, private and protected
Attribute declaration:
Method definition:
[accesstype] returntype method_name([list of para]){
method_body
}
e.g.:
public String displayName(){
System.out.print(“Dr Amos Bajeh”);
}
A Java class
Circle() {
}
Constructors
Circle(double newRadius) {
radius = newRadius;
}
double computeArea() {
return radius * radius * 3.14159; Method
}
}
Constructors, cont.
A constructor with no parameters is referred to
as a default constructor
Constructors must have the same name as the
class itself.
Constructors have no return type—not even
void.
Constructors are invoked using the new
operator when an object is created.
Constructors play the role of initializing objects.
Main method
Java provides a main method from where
execution begins.
The main method has the form:
//statements
}
Objects Creation
Object declaration:
Object declaration/creation:
}
public Employee(String n, String i, int s) // non-default constr
{
name = n;
id = i;
salary = s;
}
void display()
{
System.out.println("\nEmploye Info ");
System.out.println("Name "+ name);
System.out.println("ID "+ id);
System.out.println("Salary "+ salary);
public static void main(String[ ] args){
Employee e1 = new Employee();
e1.display();
public displayInfo(){
method_definition
}
Person
Employee
Example:
public class Person {
String name, addresss, sex;
int age;
float weight, height;
Person(String n, String a, String s,
int ag,float w, float h){
name=n; address=a; sex=s;
age=ag;weight=w;height=h;
}
public displayDetail(){
System.out.println(“NAME: “+name);
System.out.println(“ADDRESS: “+address);
System.out.println(“SEX: “+sex);
System.out.println(“AGE: “+age);
System.out.println(“WEIGHT: “+ weight);
}
}
Example:
public class Employee extends Person {
int staffNumber;
String dept;
public displayDetail(){
System.out.println(“NAME: “+name);
System.out.println(“ADDRESS: “+address);
System.out.println(“SEX: “+sex);
System.out.println(“AGE: “+age);
System.out.println(“WEIGHT: “+ weight);
System.out.println(“Number: “+staffNumber);
System.out.println(“DEPT: “+ dept);
}
}
Points to note about inheritance
The inherited attributes/methods can be used directly, just like any other fields.
You can declare a attribute/method in the subclass with the same name as the one in the superclass,
thus hiding it .
You can declare new attributes/methods in the subclass that are not in the superclass.
You can write a new instance method in the subclass that has the same signature as the one in the superclass,
thus overriding it –method overriding
You can write a new static method in the subclass that has the same signature as the one in the superclass,
thus hiding it.
You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using
the keyword super.
A subclass does not inherit the private members of its parent class.
Inheritance and Polymorphism
Polymorphism: is the OOP feature in which two or more objects response in different forms to the same
message
Using Inheritance
Since methods can be inherited from a class and
More than one class can inherit from the same class
Inheriting classes can provide unique definitions for the same method inherited from a class
Since objects of subclasses are also objects of the super class type
Person
Employee Student
Abstract methods are methods that do not have body, just the return type and signature
method_header
}
Interface implementation
Interfacesis implemented by classes
A class implementing an interface must provide definition for all the abstract methods in the interface
The following is a syntax format for java interface implementation:
method_definition
}
Interface implementation
<<Planes>>
Rectangle Triangle
Interface implementation
try{
//the code to watch for exception
}catch(Exception e){
//code to handle the exception
}finally{
//executes however
}
Exception
Note the following about the try block
• It can be nested
• If the inner try block has no matching catch, the outer try
block is searched for a match
see demo
Exception
• The throws clause
• This clause is used to indicate that a method can throw
some exceptions which the method did not provide
handler for. Thus, the user of the method should provide a
way of handling the exception(s)
https://docs.oracle.com/javase/tutorial/essent
ial/exceptions/definition.html
Requirements Engineering
Object Modeling:
• Is the identification and representation of the objects, the
operations on the objects, and relationships between the
objects
e.g.
• Sensor: roomLocation, active
Circle Cars
Class name
Circle( ) Cars( )
computeArea( ) accelerate( )
decelerate( )
methods
break( )
System
systemID
phoneNumber
masterPassword
numberOfTries
program()
arm()
disarm()
display()
dial()
Modifiers:
+ public
- private
# protected
Note the following:
The name of the class diagram should be meaningful to describe
the aspect of the system.
Each element and their relationships should be identified in
advance.
Responsibility (attributes and methods) of each class should be
clearly identified.
For each class minimum number of properties should be
specified. Because unnecessary properties will make the
diagram complicated.
Use notes whenever required to describe some aspect of the
diagram. Because at the end of the drawing it should be
understandable to the developer/coder.
Finally, before making the final version, the diagram should be
drawn on plain paper and rework as many times as possible to
make it correct.
Association Association Multiplicity
Represents relationships Indicator
between instances of
classes.
An association is a link
connecting two classes.
Bidirectional Association
denoted by e.g.
flight and plane
Unidirectional Assocation
denoted by
e.g. order and item
Example of Class Diagram