Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 1 - Introduction To OOP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 73

Object-Oriented Programming

UCCD2044 - OBJECT-ORIENTED PROGRAMMING PRACTICES


Lecturer

• Lecturer: Dr Sayed Ahmad Zikri


• Office: NG-005
• Email: zikri@utar.edu.my
• Consultation Hours:
➢ Monday & Wednesday 10:00am – 12:00pm

• Supporting Lecturers:
• Dr Chai Meei Tyng (chaimt@utar.edu.my)

2
We will be using Microsoft Teams as the
main OTL platform.

Please join the Team in Microsoft Teams


for discussion and maybe replacement
online lecture/practical classes, using
the following team code: lz18x02
Course Objective & Learning Outcomes
• Objective: To present the concepts and application of
object-oriented programming.

• Course Learning Outcomes:


CLO 1 – Write programs using advanced object-oriented concepts of
inheritance, polymorphism, abstract class and interface
CLO 2 – Construct GUI (graphical user interface) applications with
event-handling
CLO 3 – Develop applications dealing with file input/output and
databases
CLO 4 – Build multithreaded programs with appropriate exception
handling
CLO 5 – Debug and test object-oriented programs

4
Course Outlines
• Unit 1 – Introduction to Java & Object-Oriented Programming (OOP).
• Unit 2 – Methods
• Unit 3 – Classes and Objects
• Unit 4 – Arrays
• Unit 5 – Class Relationships
• Unit 6 – Inheritance & Polymorphism
• Unit 7 – Abstract Class and Interface
• Unit 8 – GUI Programming
• Unit 9 – Event Driven Programming
• Unit 10 – Exception Handling and File Input/Output
• Unit 11 – Java Database Programming
• Unit 12 – Thread and Multithreading

5
Course Information
• Assessment methods:
1. Coursework – 50%
• 1 Mid Term Test (20%) – Week 9 (Unit 1–7)
Date: TBA
Time: TBA

• 1 Practical Test (10%) – Week 11 (Unit 8 & 9)


• 1 Programming Assignment (20%) – Week 12 (Unit 1–7)
Submission deadline: TBA before 5:00 pm

2. Final Examination (FE) – 50%


(FE date & time: TBA)
Q1 – Unit 8 & 9
Q2 – Unit 10 & 11
Q3 – Unit 10 & 12
Q4 – Unit 1–7
6
Recommended Text Books & Online Sources

• Y. Daniel Liang (2017), Introduction to Java


Programming and Data Structures, Comprehension
Version, 11th ed., Pearson. (Main)
• Deitel, P.J., & Deitel, H. M. (2018), Java How to
Program. (11th ed.). Pearson
• Farrell, J. (2016), Java Programming, 8th ed., Boston,
Massachusetts: Cengage Learning.
• Gaddis, T. (2019), Starting out with Java: From Control
Structures through Objects. (6th ed.). Pearson.

• https://docs.oracle.com/javase/tutorial/index.html
• https://www.tutorialspoint.com/java/index.htm
• https://www.geeksforgeeks.org/java/ etc
7
Unit 1: Introduction to Java & Object-Oriented
Programming (OOP)

8
Unit 1 Goals
• To understand object-oriented programming (OOP) concepts
• To understand the concepts of classes and objects
• To understand Java language specifications
• To compile and run your first Java program
• To explain the basic syntax of a Java program
• To learn about types and variables
• Primitive type
• Reference type

• To realize the difference between instance variables and static


(class) variables

9
Object-Oriented Programming
(OOP)
What is Object-Oriented Programming (OOP)?
• Object-oriented programming is a programming paradigm that represents
concepts as objects that have data fields (attributes that describe the
object) and functions (methods that represent the object’s behaviour)

• An object-oriented program may be viewed as a collection of interacting


objects,
• whereas a procedure-oriented program is seen as a list of functions
(subroutines) to perform on some shared data.

Shared Data

vs.

11
Why OOP? What are the benefits?
• Code reuse – objects created for one program can easily be reused in
the other programs.

• Encapsulation – data are hidden (protected) inside an object and the


object controls how one interacts with it, preventing other kinds of errors.

• Modeling – objects in the problem domain are mapped to objects in


software, making software modeling more intuitive.

• Better design – OOP force designers to go through an extensive


planning phase, which makes for better designs with less flaws.

• Maintenance – OO programs are easier to modify and maintain than


non-OO programs.

12
What are the disadvantages?
• Effort – Object-Oriented programming is harder to learn and an OO
program requires a lot of work to create. Specifically, a great deal of
planning goes into an OO program well before a single piece of code is
ever written.

• Size & speed – Object-Oriented programs can be larger and slower than
other programs.

13
Example

• Let’s look at one problem statement:


“ …customers are allowed to have different types of bank
accounts, deposit money, withdraw money and transfer
money between accounts”
Procedural Approach
• Traditional approaches concentrate on creating functions
(procedures/operations).
• Separate data from the operation
• All data is shared: no protection
• Hard to manage complexity

bool Deposit(Account& acc, float amount);


float Withdraw(Account& acc, float amount);
void Transfer(Account& acc1, Account& acc2, float amount);

Account allAccounts[1000]; // shared data, not managed

typedef struct {
char *name;
int accountNum;
float balance;
char accountType;
} Account;
Object-Oriented Approach
• Objects in the problem domain are mapped to objects in software.
• Data and operations are grouped together
• Data are protected
class Account { Customer
private:
char *name;
int accountNum;
float balance;
char accountType;

public: Account
float withdraw();
void deposit(float amount);
void transfer(Account toAcc, float amount);
); class Customer {
private:
Account [] accounts;
Account acc1 = new Account();
acc1.deposit(100); public:
Account acc2 = new Account(); void addAccount(Account acc);
acc1.transfer(acc2, 50.0); );
Customer cus1 = new Customer();
cus1.addAccount(acc1);
Procedure-Oriented Programming vs. Object-Oriented Programming
Objects and Class Sneak Preview
Understanding Objects
• Objects are made up of attributes and methods.
• Example: a car object
• Attributes: fuel, maxspeed, model, year, price, distance, ...
• Methods: refuel(), setSpeed(), drive(), ...

• We manipulate an object by calling its methods


car.drive();

19
Class vs. Object

• A class defines a set of objects that share the same


attributes and methods (type)
– E.g.: Car class defines all types of cars
• An object is an instance of a class
– Mercedes is an instance of Car class,
– Honda is another instance of Car class
– James is an instance of Student class

In OOP, we need to
define a class first
before we can use it to
create (instantiate)
and use objects

20
Class vs. Object
• As in actual world, class (blue print/template) cannot carry out
actual performance
• Instantiation is the process whereby an object (instance) is
created from a class template.
– One may create as many object instances as desired, each has its own
copy of data fields (called instance variables)
– Once we have created an object instance, then we may manipulate the
object by calling one of its methods (called instance methods) to
perform a task or update its data fields

21
Object-Oriented Programming
• There are many more object-oriented programming concepts
such as encapsulation, inheritance, polymorphism, abstract
class, interface.

• More on objects, classes, and OOP concepts will be


discussed in future lectures.

• Next, we will introduce Java programming language and its


important features

*** Acquire basic skills of writing program (fundamentals) using primitive data types & operations, loops (control statements),
methods and arrays.
*** Methods (Lecture 2) and arrays (Lecture 4) will be cover in the lectures. 22
Java Programming Language
Top 10 Programming Languages

Source: TIOBE Index

24
The Java Programming Language
• Simple
• Object-oriented
• Platform-independent ("write once, run anywhere")
• Rich library (packages)
• Designed for the internet
• Benefits
• Safety
• Portability
Java inventor

Father of JAVA: James Gosling

25
Java – Platform Independent
Platform Dependent

myprog.c myprog.exe
gcc
(compiler) machine code
C source code

OS/Hardware

Platform Independent

myprog.java myprog.class
javac
(compiler) bytecode
Java source code
JVM
java
(interpreter)
(Java Virtual Matchine)

OS/Hardware
26
Creating, Compiling, and Running Programs

27
Java JDK vs JRE

• JDK (Java Development Kit) – is a software development


environment for developing applications (creating Java
programs) using the Java programming language.

• JRE (Java Runtime Environment) – a software bundle that


allows Java programs to run.
• Java Plug-in – a special version of the JRE designed to
run through web browsers.

28
Java JDK Version History
• JDK Alpha & Beta (1995) * Long Term Support (LTS)
• JDK 1.1 (1997)
• J2xE 1.2 (1998) – x = (E, S, M)
• J2xE 1.3 (2000)
• J2xE 1.4 (2002)
• Java 5 (2004)
• Java 6 (2006)
• Java 7 (2011)
• Java 8 (2014) – used in this class (LTS to Dec. 2020)
• Java 9 (2017) – short term release starting Java 9
• Java 10 (March 2018), Java 11 (September 2018) – (18.9 LTS)
• Java 12 (March 2019), Java 13 (September 2019)
• Java 14 (March 2020), Java 15 (September 2020 – latest version)
• Java 16 (is in Rampdown Phase)
29
Java JDK Version History
https://en.wikipedia.org/wiki/Java_version_history

30
Java – Support 3 JDK versions
• Java EE (Java Enterprise Edition)
• Business applications, server-side.
• Java SE (Java Platform Standard Edition)
• General applications, client-side.
• Java ME (Java Platform Micro Edition)
• Small devices such as mobile phone, car navigation.

31
Eclipse - Integrated Development Environment (IDE)

Popular Java IDE: Eclipse, NetBeans, IntelliJ


32
Compile and run Java program Using Command Prompt (CMD)

• Using text editor (e.g., Notepad) and save it as .java file.


Java source code files must end with the .java extension.
• To compile the Source File into a .class File from the
command line, use the javac command.
• Once you have a .class file, you can run your program. To
run a Java class from the command line, use the java
command.
Software Used

• Java SE Development Kit 8 (JDK 8 or JDK 1.8 or Java 8)


https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html

• Eclipse IDE for Java Developers 4.7 – Oxygen


https://www.eclipse.org/downloads/packages/release/oxygen/3a
https://wiki.eclipse.org/Eclipse/Installation
(current version is Eclipse 4.27 (2023-03))

Remarks: Kindly download the software from WBLE and install


it on your computer.

34
Java in action – a sneak preview
public class Car {
private String model; // attribute
private double distance;

public Car(String carModel) { // constructor


model = carModel;
}

public void drive() { // method


distance++;
}
}

public class TestAppication{

public static void main(String[] args) {


Car car1 = new Car("Honda"); Instantiation
Car car2 = new Car("BMW");
car1.drive();
car2.drive();
}
}
35
First Java Program: Welcome.java
import java.lang.System // import by default

1: public class Welcome


2: {
3: public static void main(String[] args)
4: {
5: // Display a greeting in the console window
6:
7: System.out.println("Welcome to Java!");
8: }
9: }
// Hello world in c
#include <stdio.h>

int main() {
Output: printf("Hello world\n");
return 0;
Welcome to Java!
}

36
Class
• Every Java program must have at least one class. Each class
has a name.
• Java is fully object-oriented, all codes exists in a class
(identified with class keyword).

• class <ClassName>

• The <ClassName> must be the same as the file name.


<ClassName>.java

public class Welcome {


public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

37
main Method

• If a class is run, Java will invoke/call the static main method in


that file. Similar to C++ main function.
• public static void main(String[] args) { … }

public class Welcome {


public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

38
Writing Procedural Program using Java – static method

• The static keyword identifies the method in a class that can be


used without the need to create an object instance of that class.

• A static method is similar to a function in C/C++, but in Java the


method must reside in a class.
➢ Java is fully object-oriented, all codes must exist in a class

If you apply static keyword with any method, it is known as static


method.

• A static method belongs to the class rather than object of a class.


• A static method invoked without the need for creating an instance of a
class.
• A static method can access static data member and can change the
value of it.
39
Comparison Between C/C++ and Java
#include <iostream> import java.lang.*;
using namespace std;
public class Test
int max(int, int); {
void main() public static void main(String[] args)
{ {
int a=10, b=20; int a=10, b=20;
int c= max(a, b); int c = max(a,b); // Test.max(a,b)
cout << c <<endl; System.out.println(c);
// printf("%d\n“, c);
} }

int max(int a, int b) public static int max(int a, int b)


{ {
if(a>b) if(a>b)
return a; return a;
else else
return b; return b;
} }
}
C++ Java 40
Using static method
public class ClassX public class Test
{ {
public static int max(int a, public static void main(String[] args)
int b)
{ {
if(a>b) int a=10, b=20;
return a; int c = ClassX.max(a,b);
else System.out.println(c);
return b; System.out.println(Math.sin(a));

} }
} }

• If you want to use a static method declared in another class, use the class
name and (.) to refer to the method you want to call.

ClassX.max(a,b);
Math.sin(a);

Class name
41
Java in action – a sneak preview
public class Car {
private String model; // attribute
private double distance;

public Car(String carModel) { // constructor


model = carModel;
} instance (non-static)
method
public void drive() { // method
distance++;
}
}

public class TestAppication{

public static void main(String[] args) {


Car car1 = new Car("Honda");
Car car2 = new Car("BMW");
car1.drive(); object.method()
car2.drive();
}
}
42
Standard Library
• Like C programming, Java comes with standard library – which we call the
package.

• java.lang package – Consists of common classes, such as general Math,


String, System, etc.
• You don’t need to import this, by default, Java will do it for you.

• In order to use classes in other packages, you have to first import them.
import <PackageName>.<ClassName>.

• If the package has sublevel, then it would be:


import <PackageName>.<SubPackageName>.<ClassName>
e.g.: import java.lang.System;

• If you want to include all classes in a package, use .*,


import java.io.*

• In Eclipse, press Shift+Control+O to automatically organize imports


43
Identifiers
• Identifier: name of a variable, method, or class
• Rules for identifiers in Java:
• Can be made up of letters, digits, underscore (_), and dollar sign ($)
• Cannot start with a digit
• Cannot use other symbols such as . or ? or %
• Spaces are not permitted inside identifiers
• You cannot use reserved words (keywords)
• They are case sensitive
• Examples:
➢ Valid names: studentID, s234, _sname, $100, NO_Entry
➢ Invalid names: 123D, name.com, student ID, goto

• By convention, variable and method names start with a lowercase letter


int myNumber_1
void computeArea(…)

• By convention, class names start with an uppercase letter


class Student
44
Java Keywords
abstract boolean break byte case catch char

class const continue default do double else

extends final finally float for goto if

implements import instanceof int interface long native

new package private protected public return short

static super switch synchronized this throw throws

transient try void volatile while

45
Special Symbols

Character Name Description

{} Opening and closing Denotes a block to enclose statements.


braces
() Opening and closing Used with methods.
parentheses
[] Opening and closing Denotes an array.
brackets
// Double slashes Precedes a comment line.

" " Opening and closing Enclosing a string (i.e., sequence of characters).
quotation marks
; Semicolon Marks the end of a statement.

46
Types and Variables
• Java is strongly-typed language, every variable must has a
type, which must be declared before its use
• Two different types of variables:
• Primitive type – the variables store the actual values (discuss
next)
int luckyNumber = 13; // primitive type
double total;

• Reference type – the variables store the addresses of the objects


or arrays they refer to, the referred objects must be created using
the new keyword (more in Unit 3 “Objects and Classes”)

MyClass myobject = new MyClass(); // reference type


int [] array = new int[10]; // reference type

47
Differences between Variables of
Primitive Data Types and Reference Types

Stack Heap
Primitive type: int i = 1; i 1
Reference type: Car c; c null

48
Differences between Variables of
Primitive Data Types and Reference Types

Stack Heap
Primitive type: int i = 1; i 1
c: Car
Reference type: Car c; c reference model "BMW"
distance = 0
c = new Car("BMW"); Created using new Car()

(more on this in Unit 3 “Objects and Classes”)

49
8 Primitive Types
Type Description Size
4
int The integer type, with range -2,147,483,648 . . . 2,147,483,647
bytes

byte The type describing a single byte, with range -128 . . . 127 1 byte

2
short The short integer type, with range -32768 . . . 32767
bytes

The long integer type, with range -9,223,372,036,854,775,808 . . . - 8


long
9,223,372,036,854,775,807 bytes

The double-precision floating-point type, with a range of about ±10308 and about 8
double
15 significant decimal digits bytes

The single-precision floating-point type, with a range of about ±1038 and about 4
float
7 significant decimal digits bytes

2
char The character type, representing code units in the Unicode encoding scheme
bytes

boolean The type with the two truth values: false and true 1 bit

50
Number Types
• int: integers, no fractional part
1, -4, 0

• double: floating-point numbers (double precision)


0.5, -3.11111, 4.3E24, 1E-14
• float: floating-point numbers( have to use f at the end of the number)
float a = 10.02f;
• long: have to add L at the end of the number
long a = 1000000000000L;

• A numeric computation overflows if the result falls outside the


range for the number type:
short n = (short)100000;
System.out.println(n); // prints -31072

51
Explicit Casting
• Casting is an operation that converts a value of one data
type into a value of another data type
• Casting a type with a small range to a type with a larger
range (e.g. int to double) is known as widening a type.
• Casting a type with a large range to a type with a smaller
range (e.g. double to int) is known as narrowing a type.
• Java will automatically widen a type, but you must narrow
a type explicitly.
int a = 10;
double b = 7.3;
b = a; // ok
a = b; // NOT ok
a = (int) b; // ok

52
Character Data Type
char letter = 'A';
char numChar = '4'; Four hexadecimal digits.

char letter = '\u0041'; (Unicode)


char numChar = '\u0034'; (Unicode)

• Java characters use Unicode, a 16-bit encoding scheme to


support the interchange, processing, and display of written texts
in the world’s diverse languages.
• Unicode takes two bytes, preceded by \u, expressed in four
hexadecimal numbers that run from '\u0000' to '\uFFFF'. So,
Unicode can represent 65536 characters.

53
ASCII Character Set

ASCII Character Set is a subset of the Unicode from \u0000 to


\u007F

54
Primitive Data Types as Objects
• Owing to performance considerations, primitive data type
values are not objects in Java.
• However, some Java methods require the use of objects
as arguments. Java offers a convenient way to incorporate,
or wrap, a primitive data type into an object.
• Java provides Boolean, Character, Double, Float, Byte,
Short, Integer, and Long wrapper classes in the java.lang
package for primitive data types.
• Java allows primitive types and wrapper classes to be
converted automatically.
Integer intObj = 3; // boxing
int i = intObj; // unboxing

55
The String Type

• The char type only represents one character. To represent a string of


characters, use the data type called String. For example,

String message = "Welcome to Java";

• String is actually a predefined class in the Java library just like the
System class.

• The String type is not a primitive type, it is a reference type.

• Reference data types (classes and arrays) will be thoroughly discussed


in Unit 3 & 4. For the time being, you just need to know how to declare a
String variable, how to assign a string to the variable, and how to
concatenate strings.

56
String Concatenation

// s0 = "Welcome to Java"
String s0= "Welcome " + "to " + "Java";

// s1 = "Chapter2"
String s1 = "Chapter" + 2;

// s2 = "SupplementB"
String s2 = "Supplement" + 'B';

57
Converting Strings to Integers

• To convert a String into an int value, you can use the static
parseInt method in the Integer class as follows:

int i = Integer.parseInt("257");

• To convert an int into a String object, you can use the static
toString method in the Integer class as follows:

String s = Integer.toString(i);

58
Converting Strings to Doubles

• To convert a String into a double value, you can use the


static parseDouble method in the Double class as follows:

double d = Double.parseDouble("23.57");

• To convert a double into a String object, you can use the


static toString method in the Double class as follows:

String s = Double.toString(d);

59
Constants
• Constant – value is fixed for the entire execution of your
program
Note: In Java, const is a
• Declare with keyword final, reserved keyword. It is
not used.
final int NUM_STUDENT = 1000;

• Once a constant variable is defined, its value cannot be


changed:
NUM_STUDENT = 0; // compile error!

• Java API has defined some useful constants, such as:

Math.E; // Euler number 2.71828


Math.PI; // 3.14159

60
Numeric Operators
Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2

Operator Example Equivalent


+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
++ i++ i = i + 1
-- i-- i = i - 1

61
Integer Division

5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the division)

62
Logical Operators

Java Mathematics Name Example Result


Operator Symbol (radius is 5)

< < less than radius < 0 false


<= ≤ less than or equal to radius <= 0 false
> > greater than radius > 0 true
>= ≥ greater than or equal to radius >= 0 true
== = equal to radius == 0 false
!= ≠ not equal to radius != 0 true

Operator Name
! not
&& and
|| or
^ exclusive or

63
Flow of Control

• The flow of control statements in Java are similar to C/C++

• Selections (Liang YD 2017, Ch. 3)


• if-elseif-else statement
• switch-case statement

• Loops (Liang YD 2017, Ch. 5)


• while statement
• do-while statement
• for statement

64
Selections Statement Syntax

The if-else statement has The switch-case statement has the


the following syntax: following syntax:

if ( expression ) switch (expression)


{
statement case value1:
else(opt) statement1;
break;
else-statement(opt)
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

65
Examples: selections

if (score >= 90.0) switch (status) {


System.out.print("A"); case 0:
else if (score >= 80.0) // statements;
System.out.print("B"); break;
else if (score >= 70.0) case 1:
System.out.print("C");
// statements;
else if (score >= 60.0)
break;
System.out.print("D");
else case 2: case 3:
System.out.print("F"); // statements;
break;
default:
System.out.println("Errors:
invalid status");
System.exit(1);
}

66
Loops Statement Syntax
The while loop statement has the following
syntax:
while(condition){
// statements
}
The do-while loop statement has the following
syntax:
do{
// statements
}while(condition);
The for loop statement has the following
syntax:
for(initialization; condition;
increment/decrement){
//statements (For Body)
}
67
Examples: loops

int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
count++;
}

for (int i = 0; i < 100; i++) {


if(i == 50)
continue;
System.out.println( "Welcome to Java!");
}

68
Programming Errors

• Syntax Errors
• Detected by the compiler

• Runtime Errors
• Causes the program to abort

• Logic Errors
• Produces incorrect result
• Detected (hopefully) through testing

69
Syntax Errors

public class ShowSyntaxErrors {


public static main(String[] args) {
System.out.println("Welcome to Java);
}
}

missing "

70
Runtime Errors

public class ShowRuntimeErrors {


public static void main(String[] args) {
System.out.println(1 / 0);
}
}

divided by zero

71
Logic Errors

public class ShowLogicErrors {


public static void main(String[] args) {
System.out.println("Celsius 35 is Fahrenheit degree ");
System.out.println((9 / 5) * 35 + 32);
}
}

integer division:
9/5 = 1 (not 1.8)
Output:
Celsius 35 is Fahrenheit degree
67 (true answer = 95)

72
What’s next...

• We will discuss methods in the next lecture.


• Objects, classes and OOP concepts will be covered in
Unit 3 and later lectures.

73

You might also like