You are on page 1of 60

MCS

CS212-Object Oriented
Programming
Lecture 0
Orientation
(Feb 2023)
Instructor: Lt Col Muhammad Imran Javaid
Email: imranjavaid@mcs.edu.pk

Military College of Signals , NUST

1
Prerequisite
CS114 - Fundamentals of Programming
• Course Objectives • Course Contents
– Identify the syntax and semantics of – Introduction to Computing
simple programs. – C++ Language
– Design programs using sequential, Fundamentals
selection or repetition structures – Data-Types
– Design functions to simplify the – Structures
solutions of complex problems. – Control Structures
– Implement programs using functions, – Arrays
sequential, selection or repetition – Functions
structures. – Pointers

2
CS212-Object Oriented Programming
Course Objectives
• Course Objectives
– Explain the difference between procedural and object oriented
programming paradigms
– Demonstrate the ability to create and use OOP constructs to map
real world scenarios
– Develop programs using object-oriented techniques
– Use the latest IDEs to enable quick development, testing,
documentation and packaging of programs.

3
CS212-Object Oriented Programming
Course Objectives
The student will demonstrate competency by being able to :

Sr CLO PLO Level Domain Assessment

1 Explain the difference between procedural and


PLO1 High C2 Lec
object oriented programming paradigms
2 Demonstrate the ability to create and use OOP
PLO2 High C5 Lec
constructs to map real world scenarios
3
Develop programs using object-oriented techniques PLO3 High C3 Lec

4 Use the latest IDEs to enable quick development,


PLO5 High C3/ P4 Lec/ Prac
testing, documentation and packaging of programs.

4
Course Contents
• Java Language Fundamentals • Interfaces
– Input/Output/Operators/Logical Operators/ • Exception/ Event Handling
Control statements/ Methods
• GUI/ Graphics Components
• Arrays, Array List and Strings
• Files and Streams
• Structured programming vs. Object
• Some useful Java features
Oriented Programming
• Object Oriented Concepts
• Classes and Objects
• Inheritance
• Method Overloading
• Polymorphism
5
Text Books
• Text Book:
– Java How to Program Early Objects, latest edition
• Author: Paul Deitel and Harvey Deitel
• Publisher: Pearson

• Reference Books & Online Tutorials


– “Head First Object-Oriented Design and Analysis” by O'Reilly, latest ed
– “JJJ (Java, Java, Java ) Object-Oriented Problem Solving” by R. Morelli and R. Walde, latest
ed
– “Introduction to Java Programming” by Y. Daniel Liang, , latest ed
– “Thinking in Java” by Bruce Eckel, latest ed
– “Data Structures and Abstractions with Java” by Frank M. Carrano , latest ed
6
Schedule – EE 59 A
Tuesday Friday Monday
Wk Start End 1 x Lecture 2 x Lecture Lab
0800 – 0850 hrs 1045 – 1230 hrs 0800-1050 hrs
1 13-Feb 17-Feb

2 20-Feb 24-Feb Project Progress Report -1

3 27-Feb 3-Mar

4 6-Mar 10-Mar

5 13-Mar 17-Mar Problem Based Learning Asg -1

6 20-Mar 24-Mar
7 27-Mar 31-Mar Mids

8 3-Apr 7-Apr
Project Progress Report -2
9 10-Apr 14-Apr

10 17-Apr 21-Apr

11 24-Apr 28-Apr

12 1-May 5-May Problem Based Learning Asg -2

13 8-May 12-May

14 15-May 19-May Final Project

15 22-May 26-May

16 29-May 2-Jun Final Exams

7
Schedule – EE 59 B
Wednesday Thursday Tuesday
Wk Start End 1 x Lecture 2 x Lecture Lab
0800 – 0850 hrs 1215 – 1400 hrs 1215 – 1400 hrs
1 13-Feb 17-Feb

2 20-Feb 24-Feb Project Progress Report -1

3 27-Feb 3-Mar

4 6-Mar 10-Mar

5 13-Mar 17-Mar Problem Based Learning Asg -1

6 20-Mar 24-Mar
7 27-Mar 31-Mar Mids

8 3-Apr 7-Apr

9 10-Apr 14-Apr Project Progress Report -2

10 17-Apr 21-Apr

11 24-Apr 28-Apr

12 1-May 5-May Problem Based Learning Asg -2

13 8-May 12-May

14 15-May 19-May Final Project

15 22-May 26-May

16 29-May 2-Jun Final Exams

8
LMS ENROLMENT CODE

• EE 59 A : 487056293

• EE 59 B : 951620483

9
Policies
• Communications. Announcements regarding the course, including
assignments, schedule changes, etc. will be passed through LMS.
Assignments will be submitted at LMS.
• Contact Time. Students are welcome to stop by the instructor's office
during office hours on any working day
• Evaluation
– Final : 40 %
– Mids : 30 %
– Semester Project : 10 % (2% Individual Report 1 + 2% Individual Report 2 + 6% Demo and
Presentation, Individual Report )
– Assignment : 10 % ( 2xProblem Based Learning Assignment 5% + Other Assignments 5%)
– Quiz : 10 %
• Deadlines. Deadlines are firm.
• Penalties. No penalties as deadline missed means marks missed so No late
10 submissions.
Policies
• Plagiarism
– A student should never take someone else's material and present it as
their own. Doing so means committing plagiarism.
– The term "material" here refers to ideas, words, code, or any other
piece of intellectual work, including suggestions and corrections
regarding the student's own work.
– Using someone else's material in coding assignments may be
appropriate. E.g in creating software for a homework, a student may
want to use external libraries, programs, code fragments, or other
external software artifacts. In every such case, whether the external
material is used verbatim or with modifications, the student must
always clearly identify the external material, and acknowledge its
source. Failing to do so means committing plagiarism.
11
Policies
– Less than 20% plagiarism for every assignment/ project (including
code)
• Plagiarism check of ONLY Turnitin is accepted
• Complete PDF file received from Turnitin to be uploaded
• You will find Turnitin subscription as a subject in your LMS
profile.
• In order to avoid, last minute issues. Don’t wait for deadline.
• In case one day has passed and your plagiarism check is not
complete than resubmit it

12
Policies
• Artificial intelligence tools are used to check each homework
assignment
– The software is very accurate!
– It tests your code and also notices similarities between code written
by different people
– while it might seem tempting to borrow a solution from a buddy,
change the variable names and comments, or reorder the statements,
tools would be very likely to figure out what you did
• Sure, you can fool this software
– but it’s easier and require less time to just do the assignments than
making an effort to fool the software
– … and if you try to fool it and screw up, you might fail the
13
assignment or even the whole course.
Semester Project
• 1 x Semester project which can be hardware based or software based

– Software Based : JAVA

14
JAVA Based Semester Project
• Some Ideas
– Airlines Reservation System – Mail Server
– Bug Tracking System – Network Packet Sniffer
– Career Information Management System– Number Guessing Game
– Course Management System – Online Attendance Management System
– Currency Converter – Online Bank Management System
– Data Visualization Software – Online Book Store
– Digital Steganography – Online Customer Care and Service Center
– E Health Care Management System – Online Document Management System
– Electricity Billing System – Online Examination Management System
– Email Client Software – Online Medical Management System
– Event Management System – Online Survey System
– Telephone Billing System – RSS Feed Reader
– File Transfer and Chat – Smart City Project
– Library Management System – Stock Management System
15 – Supply Chain Management System
Programming Paradigms
• A programming paradigm is a style of building the structure and
elements of computer programs
– A way of thinking about software construction
– Does not refer to a specific language but rather to a way to program, a methodology
– Some languages make it easier to write in some paradigms but not others

• Examples
– Unstructured Programming
– Procedural Programming
– Modular Programming
– Object Oriented Programming

16
Unstructured Programming
• A program that contains only one main program
– Main program stands for a sequence of commands or statements which modify data
which is global throughout the whole program
• This programming technique provides tremendous disadvantages
once the program gets sufficiently large
– For example, if the same statement sequence is needed at different locations within
the program, the sequence must be copied
• This has lead to the idea of extracting these sequences, naming them
and offering a technique to call and return from these procedures

17
Procedural Programming
• Combine returning sequences of statements into one single place
– A procedure call is used to invoke the procedure
– After the sequence is processed, flow of control proceeds right after the position
where the call was made
• With the introduction of parameters as well as procedures of
procedures (sub-procedures) programs can now be written more
structured and error free
– For example, if a procedure is correct, every time it is used it produces correct
results

18
Procedural Programming
• The main program is responsible to pass data to the individual calls,
– the data is processed by the procedures and,
– once the program has finished, the resulting data is presented
• Now we have a single program which is divided into small pieces
called procedures
• To enable usage of general procedures or groups of procedures also
in other programs, they must be separately available
– For that reason, modular programming allows grouping of procedures into modules

19
Modular Programming
• During the 1970s it became clear that even well-structured programs
were not enough for mastering the complexity involved in
developing a large program system
– It was also recognized that it was necessary to support the division of the program
into well-defined parts or modules, that could be developed and tested
independently of one another, so that several people could work together within one
large programming project
• Modular programming is thus concerned with the subdivision of
programs into manageable "chunks"

20
Modular Programming

Generate
Payroll

Get Payroll Calculate Net


Print Check
Record Pay

Validate Update
Read Payroll Calculate Calculate
Payroll Employee
Record Gross Pay Deductions
Record Record

Calculate Calculate SS
Tax withheld witheld

21
Modular Programming
• With modular programming procedures of a common functionality
are grouped together into separate modules
• A program therefore no longer consists of only one single part
– It is now divided into several smaller parts which interact through procedure calls
and which form the whole program
• Each module can have its own data. This allows each module to
manage an internal state which is modified by calls to procedures of
this module
– There is only one state per module and each module exists at most once in the
whole program

22
Programming Paradigms

Unstructured
The main
program Procedural
directly
operates on The main program
global data coordinates calls to
procedures and hands
over appropriate data Modular
as parameters
The main program coordinates
calls to procedures in separate
modules and hands over
appropriate data as parameters
23
Problems of Procedural Approach
• Data and code that operates on this data are not tightly coupled
• Data is generally made globally accessible to all functions
– Inadvertent changes to data may occur

24
Object Oriented Programming
• An object represents an entity in the real world that can be distinctly
identified, e.g., students, dogs, cars, cats, books
• Every real-world object has:
• State – information that the object stores.
• Behavior – functionality of the object, i.e., what the object can do.
• Example:
• Consider a system managing university students.
• A student object has:
• State – id, name, age, contact number, completed courses, current courses
• Behavior – enroll in course, change contact no, change enrolment degree
• A software object’s state is represented by its variables, called data fields
• A software object implements its behavior with methods.
• Every object is a bundle of variables and related methods.
• Two objects of the same kind would have the same set of behaviors, but
25
independent state information
Object Oriented Programming
• Classes and objects are the two main aspects of object-oriented
programming.
• The definition of a particular kind of objects is called a class.
– Class is a template for objects which has variables and methods
• Once created, an object is an instance of a class
– When the individual objects are created, they inherit all the variables and methods from
the class.

CLASS OBJECT
FRUIT APPLE, ORANGE, BANANA
CAR HONDA, AUDI, BMW

26 PERSON STUDENT, TEACHER, LAB ASSISTANT


Object Oriented Programming
• Objects of the program interact by program
sending messages to each other
• Objects made in a program can be object1
data object4
reused by any other program data
– This increases the reusability of the
programs once written object3
data
• The programs written in an OOP
can be easily updated by using the
object2
facilities of inheritance data

27
Object Oriented Programming
• Procedural programming is about writing procedures or methods
that perform operations on the data, while object-oriented
programming is about creating objects that contain both data and
methods.

• Object-oriented programming has several advantages over


procedural programming:
– OOP is faster and easier to execute
– OOP provides a clear structure for the programs
– OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug
– OOP makes it possible to create full reusable applications with less code and shorter
development time
28
OOP Features
• Encapsulation
• Inheritance and reuse
• Creating new Data types
• Polymorphism
• Overloading

29
Encapsulation
• Both the data, and the functionality that could affect or display that
data are included under a unified name (the object name itself).
• In the classic definition, the data elements (or properties of the
object) are not available to the outside world directly.
• Instead, methods would be created to give access to these values
outside of the object
• Now we have the ability to declare properties as being public or
private

30
Inheritance and Reuse
• This feature allows developers to define objects in a hierarchy much
like a taxonomy chart
• Each level of the hierarchy defines a more specific object than the
parent level
• Each level inherits all the properties and methods of it's parent object
and at that point you define the more specific properties and methods
need by the new level of object you created

31
Creating New Data Types
• OOP provides the programmer a convenient way to construct new data
types
– Suppose you want to represent the location of something in the form of
its x and y coordinates and want to add them like normal arithmetic
operations

location1 = location2 + origin

– Where each of these variables represents a pair of numerical quantities


– This can be done with the help of objects and classes

32
Polymorphism
• At any level of an object hierarchy each object could have a method of the
same name and because of the level at which the method resides in, it
could know which of the procedures or functions to call
• Hence you could have a Shape object that has a Draw method
– Then you could define a Circle, Square and Triangle object as Shape objects and
override the Draw method to draw specifically a Circle, Square or Triangle method
respectively
– All 4 objects would then have a Draw method but only the right method for the right
object would be called

33
Overloading
• When an existing operator such as + or = is given the capability to
operate on a new data type such as our location object in the
previous example

34
Why study OOP?
• Most widely used programming paradigm for the past 3 decades

• Offers a natural modeling paradigm for solving real life problems

• Superior way of organizing software and handling functionality


(interaction)

• Arguably the only practical way to manage the complexity of large


applications and systems

• Nearly all major programming languages we use today are OOP based
35
Classification of Programming
Languages
• Machine languages
– Strings of numbers giving machine specific instructions
– Example:
+1300042774
+1400593419
+1200274027

• Assembly languages
– English-like abbreviations representing elementary computer operations (translated via assemblers)
– Example:
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY

• High-level languages
– Codes similar to everyday English
– Use mathematical notations (translated via compilers)
– Example:
grossPay = basePay + overTimePay
36
High Level Language Translators
• One of the disadvantages of a high-level language is that it must be
translated to machine language

• High-level languages are translated using language translators

• There are three types of translators:


1. Assemblers
2. Compilers
3. Interpreters

37
High Level Language Translators
• Assemblers
– An assembler is a program that translates an assembly language program, written in
a particular assembly
Some language, into a particular
high-level languagesmachineare
language
• Compilers compiled while others are interpreted.
– A compiler is a program that translates a high-level language program, written in a
particular high-level language, into a particular machine language
There are also languages, like Java,
• Interpreters which are first complied and then
– An interpreter is a program thatinterpreted
translates a high-level language program, one
instruction at a time, into machine language.
• As each instruction is translated it is immediately executed
• Interpreted programs are generally slower than compiled programs because compiled
programs can be optimized to get faster execution

38
How Programming Works?
Compiling the Source Code

1. Edit Editor Disk


Program is created in the
editor and stored on disk.
Preprocessor program
2. Preprocess Preprocessor Disk processes the code.
Compiler creates object code
Compiler Disk
3. Compile and stores it on disk.
Linker links the object code
Linker Disk with the libraries, creates an
4. Link executable file and stores it
Primary on disk
Loader
Memory
5. Load Loader puts program in
memory.
Disk   
6. Execute 










Primary
CPU
Memory CPU takes each instruction
and executes it, possibly
storing new data values as the
   program executes.
  
  





 39
How Programming Works?
• Programming in machine-code compiled language like C:
1. Write program code
2. Compile program code, obtain executable consisting (mainly) of machine code
code for a specific family of processors e.g given a source program, a compiler
for the x86 family of processors will produce binary files for this family of
processors
• The code produced in each case is not portable
• To make the resulting code portable, we need the concept of a virtual machine
3. Execute program: program loaded into memory and machine code is
executed by CPU

40
How Programming Works?
• Programming in bytecode interpreted language like Java:
1. Write program code
2. Compile program code to standardized machine code (Java Compiler translates
program into bytecode) and obtain executable
3. Execute program: program is loaded into machine-specific virtual machine and
interpreted
• Java Virtual Machine (JVM) is a bytecode interpreter that translates bytecode to machine cod
• Sometimes, some parts of program can be compiled to machine code by JVM for faster execution
• Goal of Java: Write once, run anywhere =⇒ reduce developer effort

41
How Programming Works?
Java Virtual Machine (JVM)
• Instead of producing a processor-specific code, Java compilers produce an
intermediate code called bytecode
• The bytecode is also a binary code but is not specific to a particular CPU
• A Java compiler will produce exactly the same bytecode no matter what
computer system is used
• The Java bytecode is then interpreted by the Java Virtual Machine (JVM)
interpreter
• Each type of computer system has its own Java interpreter that can run on
that system
• This is how Java achieves compatibility
– It does not matter on what computer system a Java program is compiled, provided
42 the target computer has a JVM
How Programming Works?
JDK vs JRE Vs JVM
• JDK is a software development kit whereas
JRE is a software bundle that allows Java
program to run, whereas JVM is an
environment for executing bytecode
• JDK contains tools for developing,
debugging, etc. JRE contains class libraries
and other supporting files, whereas
software development tools are not
included in JVM.
• JDK comes with the installer, on the other
hand, JRE only contains the environment
to execute source code whereas JVM
bundled in both software JDK and JRE.
43
How Programming Works?

44
How Programming Works?
• To be a Java programmer, we need to:
• know how to write a program,
• know how to compile a program,
• know how to run a program using the Java JVM
• . . . but this is the bare minimum. . .
• Programs must be tested to discover errors
• Errors must be found using a debugger and fixed
• Bigger programs use libraries, each implementing one specific aspect of concerns
• Teams working on source code need source control and versioning and Build tools
• While students usually lean how to write programs, they usually don’t
learn anything about testing and debugging and hence deliver useless
software until they actually learn to work in a company
• We want to do this better. . .
45
How Programming Works? Summary
• We have learned about the technical process of programming, compiling,
and executing.
• We have learned how things are a bit different if an interpreted language
is used.
• We have thought about that just programming itself is enough for hobby,
but not for productive use in a team.

46
JAVA
• Java is programming language developed by Sun Microsystems.
• A small software development team(Green Team) developed this
language in the year 1991.
• The Java language was initially called OAK which was a massive
failure.
• In 1995 Sun changed the name to Java and modified the language to
take advantage of the World Wide Web development business.
• Later, in 2009, Oracle Corporation acquired Sun Microsystems and
took ownership of two key Sun software assets: Java and Solaris.

47
JAVA
• “Most popular” programming language according to TIOBE index
• Syntax similar to C and C++, but easier due to automatic memory
management
• Designed for Object-Oriented Programming (OOP)

48
JAVA Vs C++
PARAMETER JAVA C++
No backward compatibility with any previous
Compatible with C source code,
Code language. The syntax is influenced by
except some exceptional cases..
C/C++.
C++ doesn’t support garbage
Garbage Java has built-in automatic garbage collection . Manual object
Collection collection management with the help of new
and delete keywords
No strict relationship between
The strict relationship is enforced, e.g., the class names and filenames. In
Syntax
source code for class PayRoll has to be in C++, header files and
Relationship
PayRoll.java. implementation files are used for
specific class.
• Java uses compiler and interpreter both • C++ uses only compiler
• Provides the ability to ‘write once, run • C++ is precompiled.
Compilation anywhere’ that enables it to run on all the • Compiled on every operating
operating systems which have JVM system on which the code is to
installed. be run
49
JAVA is slower since it is an interpreted
JAVA Vs C++
PARAMETER JAVA C++
The source must be recompiled for the
Bytecode classes are transferrable to platform-
Portability platform; hence the code is not
specific JVM’s.(Platform Independent)
portable.(Platform dependent)
Allows both procedural programming
Programming Support object-oriented programming model.
and object-oriented programming.
Only call through the Java Native Interface and Allows direct calls to native system
Interface
recently Java Native Access libraries.
• Inbuilt garbage collection and dynamic • C++ doesn’t support garbage
Memory memory allocation process that enables collection so memory leaks may
Management efficient memory management occur
• System controlled • Accessible to programmer
Structures JAVA doesn’t support structures C++ supports structures
Inheritance Java doesn't provide multiple inheritance C++ provide multiple Inheritance
C++ supports both operator
Overloading JAVA only support method overloading
overloading & method overloading
50
JAVA doesn’t support pointers (very limited
Pointers C++ supports pointers
support)
JAVA Applications
• Web-based Applications
• Mobile Applications (Especially Android)
• Game Development (Specially 3D)
• Enterprise Applications (Specially Network Based )
• Scientific Applications (MATLAB use Java for interacting user interface)
• Big Data technologies
• Business Applications
• Distributed Applications
• Cloud-based Applications
• Desktop GUI Applications
51
JAVA Characteristics
• Java Is Simple
– Modeled on C++ bu greatly simplified and improved
• Java Is Object-Oriented
– Inherently object oriented from the start
• Java Is Distributed
– Designed to make distributed computing easy
• Java Is Interpreted
– Java – Bytecode – Interpreter (part of JVM)
• Java Is Architecture-Neutral
– Write once, run anywhere (OS independent)
• Java Is Portable
– Programs can run on any platform without being recompiled
• Java Is Multithreaded
– No need to call procedures specific to OS to enable multithreading
• Java Is Dynamic
– New code can be loaded on-the-fly without recompilation
52
Java Resources
• General
– Java mother site @ https://www.oracle.com/technetwork/java/index.html
– Java Documentation @ https://docs.oracle.com/en/java/index.html
– The online Java tutorial @ https://docs.oracle.com/javase/tutorial/
– https://www.w3schools.com/java/java_getstarted.asp
– https://www.w3schools.com/java/java_oop.asp

• JDK (Java SE or Java Platform Standard Edition)


– JDK (Java SE) mother site @ https://www.oracle.com/technetwork/java/javase/overview/index.html
– JDK API Documentation Online @ https://docs.oracle.com/en/java/javase/17/index.html
– Ken Arnold, James Gosling and David Holmes, "The Java Programming Language",
– James Gosling, Bill Joy, Guy Steele and Gilad Bracha, "The Java Language Specification",
– JDK Demos and Samples (to be downloaded @
https://www.oracle.com/technetwork/java/javase/downloads/index.html
53
JAVA Installation
• Normally JRE is installed in most PC, To check if you have Java
installed on a Windows PC, type the following in Command Prompt
(cmd.exe):
• However, for java development you need JDK, to check type the
following in Command Prompt (cmd.exe) otherwise install it
javac
• Ways of running a program
• Any text editor (Notepad/ Notepad++ ) JRE is subset of JDK
• IDE
• There are several options for an IDE
• Netbean
• Eclipse
54 • IntelliJ IDEA
Program Compilation -
• Create a source code file JAVA

• The HelloWorld.java file contains the program source code


• We need to compile it to get an executable file (HelloWorld.class ), here
• open a console
• cd into the folder where you placed HelloWorld.java
• type javac HelloWorld.java ( javac , not java ), hit return
• a file HelloWorld.class should appear
55
Program Running - JAVA
• We now can start a Java virtual machine executing our compiled program:
• open a console
• cd into the folder with HelloWorld.class
• type java HelloWorld , hit return (make sure to type java HelloWorld , not java
HelloWorld.class or java HelloWorld.java )

• The program should execute and you “Hello World!” should appear on the console

56
Assignment 1

• Installation of JAVA (JDK) and Notepad++


– Notepad++ : Official Download Download latest version from (https://notepad-plus-
plus.org/downloads/)

• Provide a report with screen shot of each installation step at submit at


LMS

Complete Setup Guide: Download from class teams OR


https://drive.google.com/file/d/1VEOc2CRPnZ985YPlcFN9Vh0ptXwK86u
J/view?usp=sharing
57
Tracing code
• Keep track of the contents of variables
• Write down the name of each variable
• Change the value when (and only when) an assignment occurs
• When you change a value, cross out the old one and write a new one

Length in inches: 50 100


Length in cms: 254.0

58
Example 1
What is the output of the following code ? Perform a code trace.

a =7
b =3 a
c =2 3
d=4
e=a
b 7
c
a =b c 2
b=e
e=c d 4
c=d
c=e e 2
print(a, b, c, d,e)

59
Copyright Notice

The material in this presentation has been taken from textbooks,


reference books, research literature and various sources on
Internet; and compiled/edited for classroom teaching at MCS-NUST
without any infringement into the copyrights of the author(s). The
original authors retain their respective copyrights as per their
stated claims. Commercial use of the material contained herein in
full or in part through copying, publication and reproducing in any
form is strictly prohibited

60

You might also like