Module 1
Module 1
Module 1
Faculty In-charge:
Pragya Gupta
E-mail: [email protected]
8/27/2020 1
Contents
• Procedural Programming Approach
• Structured Programming Approach
• Modular Programming Approach
• Object Oriented Programming Approach
• Objects and Classes
• OOP Features
• Static and Dynamic Binding
• Cohesion and Coupling
8/27/2020 2
Objective
• Understand what is Object Oriented programming
• Understand the principles of OOP
• How is OOP different from Procedural languages
• Problems in Procedural programming and how OOP overcomes them
• Know Java features and its Runtime Environment
• Understand basic structure of a Java program
• Know about the various constituents of JDK and its development environments
8/27/2020 3
Procedural Programming Approach
• Specifying the steps the program must take to reach the desired state
• Based upon the concept of the procedure call
• Procedures:
❑ Routines, subroutines, methods, or functions that contain a series of computational steps to be
carried out
• Any given procedure might be called at any point during a program's execution,
including by other procedures or itself
• Using a procedural language, the programmer specifies language statements to
perform a sequence of algorithmic steps
8/27/2020 4
Procedural Programming Approach
• Complexity increases as the length of a program increases .
• Divide a large program into different functions or modules
• Problems with Procedural languages
❑ functions have unrestricted access to global data
❑ that they provide poor mapping to real world
❑ Procedural languages are not extensible
• Example: Fortran, C, Pascal
8/27/2020 5
Structured Programming Approach
• A technique for organizing and coding programs in which hierarchy of modules is
used
8/27/2020 6
Modular Programming Approach
• A technique for separating functionality into independent, interchangeable modules
• Sub-programs or functions
8/27/2020 7
Introduction to OOP
• A programming paradigm
• deals with concepts of object to build programs and software
applications
• Modeled around real world
• The world we live in is full of objects
• Every object has a well defined identity, attributes and behavior
• Objects exhibit the same behavior in programming.
8/27/2020 8
OOP Features
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism
8/27/2020 9
OOP Approach
•Uses "objects"
• Data structures encapsulating data fields and procedures together with their
interactions – to design applications and computer programs.
•Object-oriented programming (OOP) involves programming using
objects
•An object represents an entity in the real world that can be distinctly
identified
• For example, a student, a desk, a circle, a button, and even a loan can all be
viewed as objects
•OOP features : Data abstraction, encapsulation, polymorphism, and
inheritance
8/27/2020 10
Comparison of OO and Procedural Languages
Procedural language Object Oriented language
Separate data from function that operate on them Encapsulate data and methods in a class
Not suitable for defining abstract types Suitable for defining abstract types
Not suitable for larger applications/programs Suitable for larger programs and applications
Analysis and design not so easy Analysis and Design Made Easier
Faster Slower
Only data and procedures are there Inheritance, encapsulation and polymorphism are key
features
Use top down approach Use bottom up approach
8/27/2020 11
Java Essentials
8/27/2020 12
Java Translation
Java source
code Java
bytecode
Java
compiler
Java Bytecode
interpreter compiler
Machine
code
8/27/2020 13
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
8/27/2020 14
Java Runtime
8/27/2020 15
Java Approach
8/27/2020 16
Java Features
• Platform Independence
• Object oriented
• Compiled and interpreted
• Robust
• Security
• Strictly typed language
• Lack of pointers
• Garbage collection
• Strict compile time checking
• Sandbox security
8/27/2020 17
Java Features
• Multithreaded
• Dynamic binding
• Performance
• Networking
• No pointers
• No global variables
• Automatic Garbage collection
8/27/2020 18
Differences between C++ and Java
• Operator overloading
❑ Not supported in Java
❑ Exception is ‘+’
• Explicit boolean type
❑ Boolean is an explicit type, different from int
❑ Only two boolean literals are provided i.e. true and false
❑ These cannot be compared with integers 0 and 1 as used in some other
languages
• Array length accessible
❑ All array objects in java have a length variable associated with them to
determine the length of the array
8/27/2020 19
Differences between C++ and Java
• goto
❑ Instead of goto, break and continue are supported
• Pointers
❑ There are no pointers in Java
• null pointers reasonably caught
❑ Null pointers are caught by a NullPointerException
• Memory management
❑ Explicit destructor is not needed
❑ The use of garbage collection prevents memory leaks and referencing freed memory
• Automatic variable initialization
❑ Variables are automatically initialized except local variables
• Runtime container bounds checks
❑ The bounds of containers (arrays, strings, etc.) are checked at runtime and an
IndexOutOfBoundsException is thrown if necessary.
8/27/2020 20
Differences between C++ and Java
8/27/2020 21
Differences between C++ and Java
8/27/2020 22
JVM and JRE
JVM is a part of JRE
8/27/2020 23
Program Structure
• A Java Application
consists of a collection
of classes
• A class is a template
containing methods and
variables
8/27/2020 24
First Java Program
8/27/2020 25
First Java Program
class Example {
8/27/2020 26
Executing Java Programs
• Entering the source code: text editor like notepad or any IDE
• Saving the source code:
❑ Select File | Save As from the notepad menu
❑ In the ‘File name’ field, type “Example.java” within the double quotes
❑ In the ‘Save as type’ field select All Files (*.*).
❑ Click enter to save the file
• Compiling & running the source
❑ type cmd at the run prompt
❑ move to the folder that contains the saved Example.java file
❑ compile the program using javac
❑ C:\javaeg\>javac Example.java
8/27/2020 27
Executing Java Programs
• Compilation creates a file called Example.class
• This class contains bytecode which is interpreted by JVM.
• To execute the program type the following command at the dos
prompt:
❑ C:\javaeg\>java Example
• The output of the program is shown below:
❑ This is a simple Java program
8/27/2020 28
Why save as Example.java?
• The name of the .class file will match exactly with the name of the
source file
• That is why it is a good idea to give the Java source files the same
name as that of the class they contain
• Java is case-sensitive
• So example and Example are two different class names
8/27/2020 29
Installation of Java
8/27/2020 30
Installed Directory structure
8/27/2020 31
Installed Directory Structure
• src.zip file contains all the core class binaries, and is used by JDK in this form
• include\ directory contains a set of C and C++ header files for interacting with
C and C++
• lib\ directory contains non-core classes like dt.jar and tools.jar used by tools
and utilities in JDK
• bin\ The bin directory contains the binary executables for Java
❑ For example, Java Compiler (Java), Java Interpreter (Java)
• jre\ is the root directory for the Java runtime environment
• db\ contains java database
8/27/2020 32
Tools in JDK
8/27/2020 33
IDE
• Tools specifically designed for writing Java code.
• Tools offer a GUI environment to compile and debug your Java
program easily from the editor environment, as well as browse
through your classes etc.
• Popular IDE’s
❑ Eclipse
❑ Netbeans
❑ Kawa
❑ JCreator
8/27/2020 34
Objects and Classes
• The state of an object (also known as its properties or attributes) is
represented by data fields with their current values
• Example:
❑ A circle object has a data field radius, which characterizes a circle
❑ A rectangle object has the data fields width and height, which characterize a
rectangle
• The behavior of an object (also known as its actions) is defined by methods
• To invoke a method on an object is to ask the object to perform an action
• Example:
❑ getArea() and getPerimeter() maybe defined
❑ getArea() maybe invoked by circle object to return its area and getPerimeter() to
return its perimeter
8/27/2020 35
Objects and Classes
• Objects of the same type are defined using a common class
• A class is a template, blueprint, or contract that defines what an
object’s data fields and methods will be
• An object is an instance of a class, many instances can be created
• Creating an instance is referred to as instantiation.
• The terms object and instance are often interchangeable
8/27/2020 36
Objects
8/27/2020 37 37
Classes
8/27/2020 38 38
Classes
8/27/2020 39 39
OOP Concepts
• Key OOP Concepts
– Object, Class
– Data Abstraction
– Encapsulation
– Inheritance and Subclasses
– Polymorphism
❑ Run-time polymorphism
❑ Compile-time polymorphism
8/27/2020 40
Object
• Defined as instance of a class
• Example: table, chair are all instances of the class Furniture.
• Objects have unique identity, state and behavior
• State is defined by the attributes of the object.
• Different objects have different attributes ( characteristics)
• Example: the attributes of student are name, roll number etc
• Behavior actually determines the way an object interacts with other objects.
• Synonym to functions
8/27/2020 41
Object
8/27/2020 42
Class
8/27/2020 43
Class
8/27/2020 44
Instantiation
• Object creation
• Memory is allocated for the object’s fields as defined in the class
• Initialization is specified through a constructor
– a special method invoked when objects are created
8/27/2020 45
Abstraction
8/27/2020 46
Encapsulation
8/27/2020 47
Encapsulation
8/27/2020 48
Inheritance
• Inheritance:
– programming language feature that allows for the implicit
definition of variables/methods for a class through an existing
class
• Subclass relationship
– B is a subclass of A
– B inherits all definitions (variables/methods) in A
8/27/2020 49
Reuse
8/27/2020 50
Polymorphism
• “Many forms”
– allow several definitions under a single method name
• Example:
– “move” means something for a person object but means
something else for a car object
• Dynamic binding:
– capability of an implementation to distinguish between the
different forms during run-time
8/27/2020 51
Static and Dynamic Binding
• Association of method call to the method body is known as binding
8/27/2020 52
Static and Dynamic Binding
• If you have more than one method of same name (method overriding) or two variable of same name in
same class hierarchy it gets tricky to find out which one is used during runtime as a result of there
reference in code.
• Binding is the process used to link which method or variable to be called as result of the reference in
code.
o Most of the references is resolved during compile time but some references which depends upon Object
and polymorphism in Java is resolved during runtime when actual object is available.
o When a method call is resolved at compile time, it is known as static binding, while if method invocation is
53 8/27/2020
Lecture12 resolved at runtime, it is known as Dynamic binding or Late binding. 53
Static and Dynamic Binding
• private, final and static methods and variables uses static binding and resolved by compiler because
compiler knows that they can't be overridden and only possible methods are those, which are defined
inside a class, whose reference variable is used to call this method.
• Static binding uses Type information for binding while Dynamic binding uses Object to resolve binding.
• Static Binding
Variables are resolved using static binding which makes there execution fast because no time is wasted to find
correct method during runtime.
o Private, final, static methods – static binding
54 8/27/2020
Lecture12 54
• Dynamic Binding
Coupling
8/27/2020 55
Tight Coupling
If a class A has some public data members and another class B is accessing these data
members directly using the dot operator (which is possible because data members were
declared public), the two classes are said to be tightly coupled
Let's say, the same class A has a String data member, name, which is declared public and this
class also has getter and setter methods that have implemented some checks to make sure -
• A valid access of the data member, name i.e. it is only accessed when its value is not null,
and
• A valid setting of the data member, name i.e. it cannot be set to a null value
But these checks implemented in the methods of class A to ensure a valid access and valid
setting of its data member, name, are bypassed by its direct access by class B, due to tight
coupling between two classes.
8/27/2020 56
Tight Coupling
Program Analysis
• Class A has an instance variable, name, which is declared public
• Class A has two public getter and setter methods which check for a valid access and valid
setting of data member - name
• Class B creates an object of class A and directly sets the value of its data member, name,
to null and directly accesses its value because it was declared public
• Thus, the validity checks for the data member, name, which were implemented
within getName() and setName() methods of class A are bypassed, which shows that
class A is tightly coupled to class B, and it is a bad design
8/27/2020 57
Loose Coupling
• A good application designing is creating an application with loosely coupled classes by
following encapsulation
• i.e. by declaring data members of a class with the private access modifier, which disallows
other classes to directly access these data members, and forcing them to call
the public getter, setter methods to access these private data members
8/27/2020 58
Loose Coupling
Program Analysis
• Class A has an instance variable, name, which is declared private
• Class A has two public getter and setter methods which check for a valid access and valid
setting of the data member, name
• Class B creates an object of class A, calls the getName() and setName() methods and
their implemented checks are properly executed before the value of instance
member, name, is accessed or set
• It shows that class A is loosely coupled to class B, which is a good programming design
8/27/2020 59
Cohesion
8/27/2020 60
Low Cohesion
• When a class is designed to do many different tasks rather than focus on a single specialized
task, this class is said to be a "low cohesive" class
• Low cohesive classes are said to be badly designed, as it requires a lot of work at creating,
maintaining and updating them
Program
Example of a low cohesion class
class PlayerDatabase
{ public void connectDatabase();
public void printAllPlayersInfo();
public void printSinglePlayerInfo();
public void printRankings();
public void printEvents();
public void closeDatabase(); }
8/27/2020 61
Low Cohesion
Program Analysis
• Here, we have a class PlayerDatabase which is performing many different tasks like
connecting to a database, printing the information of all the players, printing information of a
single player, printing all the events, printing all the rankings and finally closing all opened
database connections
Now, such a class is not easy to create, maintain and update, as it is involved in performing
many different tasks i.e. a programming design to avoid
8/27/2020 62
High Cohesion
• A good application design is Program
//Example of high cohesion classes
creating an application
class PlayerDatabase {
with high cohesive classes,
ConnectDatabase connectD= new connectDatabase();
which are targeted towards PrintAllPlayersInfo allPlayer= new PrintAllPlayersInfo(); PrintRankings
8/27/2020 63
High Cohesion
Program Analysis
• Here we have created several different classes, where each class is performing a specific
specialized task, which leads to an easy creation, maintenance and modification of these classes
• Classes created by following this programming design are said to performing a cohesive role
and are termed as high cohesion classes, which is an appropriate programming design to follow
while creating an application
8/27/2020 64
Thank You
8/27/2020 65