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

Lecture 1

The document outlines the curriculum for a Programming II course focused on object-oriented programming concepts, taught by Dr. Islam Elkabani. Key topics include classes and objects, encapsulation, inheritance, polymorphism, and methods, with practical applications demonstrated through the implementation of a Point class. Evaluation criteria consist of lab assignments, quizzes, a mid-term, a final project, and a final exam.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 1

The document outlines the curriculum for a Programming II course focused on object-oriented programming concepts, taught by Dr. Islam Elkabani. Key topics include classes and objects, encapsulation, inheritance, polymorphism, and methods, with practical applications demonstrated through the implementation of a Point class. Evaluation criteria consist of lab assignments, quizzes, a mid-term, a final project, and a final exam.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

FCDS

Programming II

Lecture 1: Introduction
Instructor

Dr. Islam Elkabani

Email:
[email protected]
Text Books

Building Java Programs: A Back to Basics Approach


(4th Edition) Stuart Reges & Marty Stepp;

Y. Daniel Liang, 2020. Java How to Program:


Comprehensive Version. 12th ed. Pearson.
Course Main Objectives

• The main objective of this course is to introduce


the concepts of object oriented programming
to computer science and engineering students
to equip the students with the required skills to
design and develop large scale applications
Evaluation
Category Percentage Location Date
Lab Assignments + 15% In Lab Weekly
Quizzes

Mid Term 20% In Class 7th Lecture

Final Project 15% In Lab 13th week

Final Exam 50% In Class 15th Lecture


Course Content
• Classes and Objects
• Introduction to the Unified Modelling Language
• Encapsulation
• Inheritance
• Polymorphism
• Abstract classes and Interfaces
• Array Lists
• Searching and Sorting Lists
• Recursion
• Exception Handling
• Files I/O
Objects (Revision)
• object: An entity that contains data and behavior.
– data: variables inside the object
– behavior: methods inside the object
• You interact with the methods;
the data is hidden in the object.

• Constructing (creating) an object:


Type objectName = new Type(parameters);
• Calling an object's method:
objectName.methodName(parameters);
Methods (Revision)
• What is a Method (a function)?
A subprogram (set of java statements) used to do a certain task. A
method has zero or more inputs ( called parameters), and zero
or one output (called return value)

Inputs Method Output


(parameters) (return value)

• Example:
public static void main(String[] args) {

}
Object Oriented Programming (OOP)
Fundamentals of OOP
• Classes and Objects
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism (Overriding and
Overloading)
Classes & Objects

11
Examples of Objects

CAR BOY GIRL CLOCK

VDU BOOK TREE TRIANGLE

Figure 1.9: Examples of objects

12
What is a Class?
• Group of Objects with similar
– properties (attributes)
– behavior
– relationships to other objects

• Blueprints of Objects (Template)

13
Classes and Objects
Person Objects

Abstract Person Class


Into Attributes: Name, Age, Sex
Operations: Speak(), Listen(), Walk()

Vehicle Objects

Abstract Vehicle Class


Into Attributes: Name, Model, Color
Operations: Start(), Stop(), Accelerate()

Polygon Objects

Polygon Class
Abstract Attributes: Vertices, Border,
Into Color, FillColor
Operations: Draw(), Erase(), Move()

Figure 1.12: Objects and classes


14
Abstract Data Type (ADT)
• A structure that contains both data and the
actions to be performed on that data.
• Class is an implementation of an Abstract Data
Type.
• Object is an instance of a class.
• A class represents a template for several objects
that have common properties.

15
Abstraction
Abstraction
• An abstraction is a view or representation of an
entity that includes only the most significant
attributes.
• “The process of reducing an object to its
essence so that only the necessary elements are
represented. Abstraction defines an object in
terms of its properties (attributes), behaviors
(functionality), and interface (means of
communicating with other objects)”
17
Abstraction Example

18
Encapsulation
Encapsulation
• The technique of hiding the internal implementation detail of an
object from it’s external views.

• “Encapsulation ensures that the object providing service can


prevent other objects from manipulating its data or procedures
directly, and it enables the object requesting service to ignore the
details of how that service is provided.”

20
Inheritance
Inheritance
– Object-oriented programming allows classes to inherit
commonly used state and behavior from other
classes.

– Software reusability and extensibility

– Create new class from existing class


• Absorb existing class’s data and behaviors
• Enhance with new capabilities

22
Inheritance - Example
• Define Person to be a class
– A Person has attributes, such as name, age, height, gender
– Assign values to attributes when describing object

• Define student to be a subclass of Person


– A student has all attributes of Person, plus attributes of his/her
own (student no, course_enrolled)
– A student inherits all attributes of Person

• Define lecturer to be a subclass of Person


– Lecturer has all attributes of Person, plus attributes of his/her
own ( staff_id, subjectID1, subjectID2)

23
Polymorphism
Polymorphism
• Polymorphic which means “many forms” has Greek
roots.
– Poly – many
– Morphos - forms.

• In OO paradigm polymorphism has many forms.

• Allow a single object, method, operator associated with


different meaning depending on the type of data passed
to it.

25
Polymorphism – Method Overloading
• Multiple methods can be defined with the same name,
different input arguments (different signature).
Method 1 - initialize(int a)
Method 2 - initialize(int a, int b)

• Appropriate method will be called based on the input


arguments.
initialize(2) Method 1 will be called.
initialize(2,4) Method 2 will be called.

26
Advantages of OOP
• simplicity: software objects model real world objects, so the
complexity is reduced and the program structure is very clear

• modularity: each object forms a separate entity whose internal


workings are separated from other parts of the system

• modifiability: it is easy to make minor changes in the data


representation or the procedures in an OO program. Changes inside
a class do not affect any other part of a program

• extensibility: adding new features or responding to changing


operating environments can be solved by introducing a few new
objects and modifying some existing ones

• maintainability: objects can be maintained separately, making


locating and fixing problems easier

• re-usability: objects can be reused in different programs.


Classes and objects
• class: A program entity that represents either:
1. A program / module, or
2. A template for a new type of objects.

• object: An entity that combines state and behavior.


– object-oriented programming (OOP): Programs that
perform their behavior as interactions between objects.
Our task
• In the following slides, we will implement a Point
class as a way of learning about defining classes.

– We will define a type of objects named Point.


– Each Point object will contain x/y data called fields.
– Each Point object will contain behavior called
methods.
– Client programs will use the Point objects.
Point objects (desired)
Point p1 = new Point(5, -2);
Point p2 = new Point(); // origin, (0, 0)

• Data in each Point object:


Field Description
name
x the point's x-
coordinate
y the point's y-
• Methods incoordinate
each Point object:
Method name Description
setLocation(x, y) sets the point's x and y to the given values
translate(dx, adjusts the point's x and y by the given amounts
dy)
distance(p) how far away the point is from point p
Point class as blueprint
Point class
state:
int x, y
behavior:
setLocation(int x, int y)
translate(int dx, int dy)
distance(Point p)

Point object #1 Point object #2 Point object #3


state: state: state:
x = 5, y = -2 x = -245, y = 1897 x = 18, y = 42
behavior: behavior: behavior:
setLocation(int x, int y) setLocation(int x, int y) setLocation(int x, int y)
translate(int dx, int dy) translate(int dx, int dy) translate(int dx, int dy)
distance(Point p) distance(Point p) distance(Point p)

– The class (blueprint) will describe how to create objects.


– Each object will contain its own data and methods.
Object state: Fields
Point class, version 1
public class Point {
int x;
int y;
}
– Save this code into a file named Point.java.

• The above code creates a new type named Point.


– Each Point object contains two pieces of data:
• an int named x, and
• an int named y.

– Point objects do not contain any behavior (yet).


Fields
• field: A variable inside an object that is part of its state.
– Each object has its own copy of each field.

• Declaration syntax:
type name;

– Example:
// each Student object has a name and gpa field
public class Student {
String name;
double gpa;
}
Accessing fields
• Other classes can access/modify an object's fields.
– access: variable.field
– modify: variable.field = value;

• Example:
Point p1 = new Point();
Point p2 = new Point();
System.out.println("the x-coord is " + p1.x); // access
p2.y = 13; // modify
A class and its client
• Point.java is not, by itself, a runnable program.
– A class can be used by client programs.
PointMain.java (client program) Point.java (class of objects)
public class PointMain { public class Point {
main(String args) { int x;
Point p1 = new Point(); int y;
p1.x = 7; }
p1.y = 2;

Point p2 = new Point();


p2.x = 4; x 7 y 2
p2.y = 3;
...
}
} x 4 y 3
PointMain client example
public class PointMain {
public static void main(String[] args) {
// create two Point objects
Point p1 = new Point();
p1.y = 2;
Point p2 = new Point();
p2.x = 4;
System.out.println(p1.x + ", " + p1.y); // 0, 2
// move p2 and then print it
p2.x += 2;
p2.y++;
System.out.println(p2.x + ", " + p2.y); // 6, 1
}
}
Arrays of objects
• null : A value that does not refer to any object.
– The elements of an array of objects are initialized to null.
String[] words = new String[5];
Point[] points = new Point[3];
inde 0 1 2 3 4
words x
value null null null null null

inde 0 1 2
points x
value null null null
Two-phase initialization
1) initialize the array itself (each element is initially null)
2) initialize each element of the array to be a new object

String[] words = new String[4]; // phase 1


for (int i = 0; i < words.length; i++) {
words[i] = "word" + i; // phase 2
}
inde 0 1 2 3
words x
value "word0" "word1" "word2" "word3"
Things you can do w/ null
• store null in a variable or an array element
String s = null;
words[2] = null;

• print a null reference


System.out.println(s); // null

• ask whether a variable or array element is null


if (words[2] == null) { ...

• pass null as a parameter to a method


System.out.println(null); // null

• return null from a method (often to indicate failure)


return null;
Null pointer exception
• dereference: To access data or methods of an object with the dot
notation, such as s.length() .
– It is illegal to dereference null (causes an exception).
– null is not any object, so it has no methods or data.

String[] words = new String[5];


System.out.println("word is: " + words[0]);
words[0] = words[0].toUpperCase(); // ERROR

Output: inde 0 1 2 3 4
word is: null x
Exception in thread "main" value null null null null null
java.lang.NullPointerException
at Example.main(Example.java:8)
Looking before you leap
• You can check for null before calling an object's
methods.
String[] words = new String[5];
words[0] = "hello";
words[2] = "goodbye"; // words[1], [3], [4] are null

for (int i = 0; i < words.length; i++) {


if (words[i] != null) {
words[i] = words[i].toUpperCase();
}
}
inde 0 1 2 3 4
words x
value "HELLO" null "GOODBYE" null null
Object behavior: Methods
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 shout() {
System.out.println("HELLO THERE!");
}
Mutator method questions
• Write a method setLocation that changes a
Point's location to the (x, y) values passed.

• Write a method translate that changes a


Point's location by a given dx, dy amount.

– Modify the Point and client code to use these


methods.
Mutator method answers
public void setLocation(int newX, int newY) {
x = newX;
y = newY;
}

public void translate(int dx, int dy) {


x = x + dx;
y = y + dy;
}

// alternative solution that utilizes setLocation


public void translate(int dx, int dy) {
setLocation(x + dx, y + dy);
}
Accessor method questions
• Write a method distance that computes the distance
between a Point and another Point parameter.
x2  x1 2  y2  y1 
2

Use the formula:

• Write a method distanceFromOrigin that returns


the distance between a Point and the origin, (0, 0).

– Modify the client code to use these methods.


Accessor method answers
public double distance(Point other) {
int dx = x - other.x;
int dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}

public double distanceFromOrigin() {


return Math.sqrt(x * x + y * y);
}

// alternative solution that uses distance


public double distanceFromOrigin() {
Point origin = new Point();
return distance(origin);
}
Printing objects
• By default, Java doesn't know how to print objects:
Point p = new Point();
p.x = 10;
p.y = 7;
System.out.println("p is " + p); // p is Point@9e8c34

// better, but cumbersome; p is (10, 7)


System.out.println("p is (" + p.x + ", " + p.y + ")");

// desired behavior
System.out.println("p is " + p); // p is (10, 7)
The toString method
tells Java how to convert an object into a String

Point p1 = new Point(7, 2);


System.out.println("p1: " + p1);

// the above code is really calling the following:


System.out.println("p1: " + p1.toString());

• Every class has a toString, even if it isn't in your code.


– Default: class's name @ object's memory address (base 16)

Point@9e8c34
toString syntax
public String toString() {
code that returns a String representing this object;
}

– Method name, return, and parameters must match exactly.

– Example:
// Returns a String representing this Point.
public String toString() {
return "(" + x + ", " + y + ")";
}
- // Now
System.out.println("p is " + p); // p is (10, 7)
Object initialization: constructors
Initializing objects
• Currently it takes 3 lines to create a Point and
initialize it:
Point p = new Point();
p.x = 3;
p.y = 8; // tedious

• We'd rather specify the fields' initial values at the start:


Point p = new Point(3, 8); // better!

– We are able to do this with most types of objects in Java.


Constructors
• constructor: Initializes the state of new objects.
public type(parameters) {
statements;
}

– runs when the client uses the new keyword

– no return type is specified;


it implicitly "returns" the new object being created

– If a class has no constructor, Java gives it a default constructor with no


parameters that sets all fields to 0 or null.
Constructor example
(Point class, version 2)
public class Point {
int x;
int y;

// Constructs a Point at the given x/y location.


public Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}

public void translate(int dx, int dy) {


x = x + dx;
y = y + dy;
}

...
}
Tracing a constructor call
• What happens when the following call is made?
Point p1 = new Point(7, 2);

p1 x 7 y 2

public Point(int initialX, int initialY) {


x = initialX;
y = initialY;
}

public void translate(int dx, int dy) {


x += dx;
y += dy;
}
Client code, version 2
public class PointMain2 {
public static void main(String[] args) {
// create two Point objects
Point p1 = new Point(5, 2);
Point p2 = new Point(4, 3);
// print each point
System.out.println("p1: (" + p1.x + ", " + p1.y + ")");
System.out.println("p2: (" + p2.x + ", " + p2.y + ")");
// move p2 and then print it again
p2.translate(2, 4);
System.out.println("p2: (" + p2.x + ", " + p2.y + ")");
}
}
OUTPUT:
p1: (5, 2)
p2: (4, 3)
p2: (6, 7)
Multiple constructors
• A class can have multiple constructors.
– Each one must accept a unique set of parameters.

• Exercise: Write a Point constructor with no parameters that


initializes the point to (0, 0).

// Constructs a new point at (0, 0).


public Point() {
x = 0;
y = 0;
}
Common constructor bugs
1. Re-declaring fields as local variables ("shadowing"):
public Point(int initialX, int initialY) {
int x = initialX;
int y = initialY;
}

– This declares local variables with the same name as the fields,
rather than storing values into the fields. The fields remain 0.

2. Accidentally giving the constructor a return type:


public void Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}

– This is actually not a constructor, but a method named Point

You might also like