Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
23 views52 pages

Chapter - 1 - Introduction To OOP

This document introduces Object-Oriented Programming (OOP) and its key concepts, including classes, objects, encapsulation, inheritance, abstraction, and polymorphism. It contrasts OOP with structured programming paradigms, highlighting the advantages of OOP in managing complexity and promoting code reusability. Additionally, it covers the history of Java, its features, and the phases involved in creating and executing a Java application.

Uploaded by

guyoboru12345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views52 pages

Chapter - 1 - Introduction To OOP

This document introduces Object-Oriented Programming (OOP) and its key concepts, including classes, objects, encapsulation, inheritance, abstraction, and polymorphism. It contrasts OOP with structured programming paradigms, highlighting the advantages of OOP in managing complexity and promoting code reusability. Additionally, it covers the history of Java, its features, and the phases involved in creating and executing a Java application.

Uploaded by

guyoboru12345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

CHAPTER 1

INTRODUCTION TO OBJECT
ORIENTED PROGRAMMING

1
CONTENTS

▪ What is Programming? ▪ Abstraction


▪ What is Programming Paradigm? ▪ Polymorphism
▪ Class ▪ Encapsulation
▪ Objects ▪ Phases of java Programs
▪ Class Members
▪ Inheritance

2
WHAT IS PROGRAMMING?

3
PROGRAMMING PARADIGMS

• It is a fundamental style or approaches of programming languages.

• The paradigm of the programming language determines how you will


solve a problem.

• A classification of programming languages based on their features (but most popular


languages support multiple paradigms)

• Generally, there are two types of programming paradigms:

▪ Structured(Process-Oriented) Programming Paradigms

▪ Object Oriented Programming Paradigms (OOP) 4


STRUCTURED(PROCESS-ORIENTED) PROGRAMMING PARADIGMS

• In this approach, the problem is viewed as the sequence of things to be done such as
reading, calculating and printing.

• Languages such as Cobol, Fortran, C, and C++ are examples of structured programming
language.

• The primary focus of this paradigm is on functions.

• In structured programming paradigm, programs are written around code "what is


happening?“

• The program is organized-code acting on data and it is suitable only for small
programs or problems.

• The technique of hierarchical decomposition has been used to specify the tasks to be
completed for solving a problem. 5
▪ Fig 1:1 : A typical structure for procedural programming
6
CONT.…

• Procedure/Function oriented programming basically consists of writing a list of


instructions for the computer to follow, and organizing these instructions into
groups known as functions.

• We normally use flowcharts to organize these actions and represent the flow of control
from one action to another.

• In a multi-function program, many important data items are placed as global so that
they may be accessed by all functions. Each function may have its own local data.

• Global data are more vulnerable to accidental change by a function.

• In a large program it is very difficult to identify what data is used by which


function. 7
CONT.

• This provides an opportunity for bugs to creep in.


• Another serious drawback with the procedural approach is that it does not model
real world problems very well.
• This is because functions are action-oriented and do not really
corresponding to the element of the problem.

• Some characteristics exhibited by procedure-oriented programming are:


• Emphasis is on doing things (algorithms)
• Large programs are divided into smaller programs known as functions
• Most of the functions share global data.
• Data move openly around the system from function to function.
8
OBJECT ORIENTED PROGRAMMING PARADIGMS

• Problems with structured programming approach appear as programs grow larger and more
complex.

• To manage increasing complexity, the second approach, called object-oriented programming, was
conceived.

• OOP organizes a program around its data (that is, objects) and a set of well-defined interfaces
to that data.

• OOP allows us to decompose a problem into a number of entities called objects and then
build data and methods (functions) around these entities.

• Structured programming is a subset of object-oriented programming.

• Therefore, OOP can help in developing much larger and complex programs than structured
programming.
9
➢Fig: Shows the organization of data and function in object-oriented programs.
▪ The data of an object can be accessed only by the function (methods) associated
with that object.
▪ However, function (method) of one object can access the function (method) of other
objects
10
SOME OF THE FEATURES OF OBJECT-ORIENTED PROGRAMMING ARE:

• Emphasis is on data rather than procedure.

• Programs are divided into what are known as objects.

• Functions (methods) that operate on the data of an object are tied


together in the data structure.

• Data is hidden and cannot be accessed directly by external function.

• Objects may communicate with each other through function.

• New data and functions can be easily added whenever necessary.


11
STRUCTURED PROGRAMMING VERSUS OBJECT ORIENTED
PROGRAMMING
Structured Programming Object Oriented Programming
▪ Both functions and data is considered ▪ Data and methods are tied together since
separate because data structures are variables and methods are well organized
not well organized within the under classes
program
▪ Programs are divided into small self ▪ Programs are divided into small entities
contained functions called objects
▪ Functions or procedures are the basic ▪ Objects are the basic units of
units of manipulation in structured manipulation in object oriented
programming programming

▪ Structured Programming follows top- ▪ Object Oriented Programming follows


down approaches bottom-up approaches
12
STRUCTURED PROGRAMMING VERSUS OBJECT ORIENTED
PROGRAMMING

▪ A program is focused on ▪ A program is focused on the


manipulation of data. manipulation of both data (classes
and states of objects) and on
methods.
▪ Structured programming is ▪ Data is hidden within the objects and
less secure as there is no way its manipulation can be strictly
of data hiding controlled in OOP
▪ Structured Programming ▪ OOP supports reuses of classes and
misses reuses of classes, their parts of the code and supports
codes and inheritance the inheritance of state and behavior
13
CLASS AND OBJECT

▪ A class can be defined as a template or blueprint that describes the attributes (state)
and behaviors (methods) that its objects will have.

▪ A class encapsulates data (attributes or fields) and methods (functions) that


operate on that data.

▪ It acts as a template from which individual objects can be created. In other words, a
class defines what an object will be and how it will behave.

▪ A group of objects that share common properties for data part and some program
part are collectively called as class.

14
CLASS AND OBJECT

▪ For example, a class that represents a bank account might contain one method to
deposit money to an account, another to withdraw money from an account and a
third to inquire what the account’s current balance is.

▪ A class that represent a House might contain one method to open door ,another
to close the door. And states like color, Height, width. 15
OBJECT

▪ Objects are instances of classes in object-oriented programming.

▪ They represent real-world entities and encapsulate both data (states) and the methods
(behaviours) that operate on the data.

▪ States: Objects
▪ States represent the characteristics or attributes of an object.

▪ example, a dog object might have states such as colour and name. State Behavior
▪ Behaviours:

▪ Behaviours represent the actions or operations that an object can perform.

▪ example, a dog object might have behaviours such as wagging, barking, and eating.
16
Classes and Objects

▪ In this example, , we can see that a class Person has been defined with the data members ‘unique_id’, ‘name’,
‘age’, ‘city’ and ‘gender’ and methods ‘eat()’, ‘study()’, ‘sleep()’ and ‘play()’.
▪ Two objects of this class have been defined.
▪ The first object has ‘name’ as ‘Parsoon’, ‘age’ as ‘25’, ‘city’ as ‘Delhi’ and ‘gender’ as ‘male’.
▪ The second object of the ‘Person’ class has ‘name’ as ‘Purva’, ‘age’ as ‘28’, ‘city’ as ‘Goa’ and ‘gender’ as
17
‘female’.
VARIABLES

➢ A class can contain any of the following variable types

➢Local Variables :- Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable will
be destroyed when the method has completed.

➢Instance variables:- Instance variables are variables that are declared within a class but
outside any method. These variables are instantiated when the class is loaded. Instance
variables can be accessed from inside any method, constructor or blocks of that particular
class.

➢Class variables :- Class variables are variables declared with in a class, outside any method,
with the static keyword. 18
METHODS AND CONSTRUCTORS

➢ Methods
▪ A method is basically a behavior. A class can contain many methods. It is in methods
where the logics are written, data is manipulated and all the actions are
executed.

➢ Constructors

▪ Every class has a constructor. If we do not explicitly write a constructor for a class
the Java compiler builds a default constructor for that class.

▪ Each time a new object is created, at least one constructor will be invoked. The
main rule of constructors is that they should have the same name as the class.

▪ A class can have more than one constructor. 19


PILLARS OF OBJECT-ORIENTED PROGRAMMING

➢ There are four major pillars of Object-oriented Programming .


These are:-

Encapsulation
Inheritance
Abstraction
Polymorphism
20
ENCAPSULATION

▪ Encapsulation is the technique of restricting direct access to the fields of a


class by making them private and providing controlled access through public
methods (getters and setters).

▪ When a field is declared private, it cannot be accessed directly from outside the
class, thereby hiding the fields within the class.

▪ For this reason, encapsulation is also referred to as data hiding.

▪ Encapsulation acts as a protective barrier that prevents direct modification


of data, ensuring better control over how data is accessed and modified.

21
INHERITANCE

▪ Inheritance is the process by which one class acquires the properties


(fields and methods) of another class.

▪ It helps organize information in a hierarchical manner, making code more


reusable and manageable.

▪ The class that inherits properties is called the subclass (also known as the
derived class or child class).

▪ The class whose properties are inherited is called the superclass (also
known as the base class or parent class).

▪ In Java, the extends keyword is used to establish inheritance between classes. 22


ABSTRACTION

▪ As per dictionary, abstraction is the quality of dealing with ideas rather than events.

▪ In object-oriented programming, abstraction is the process of hiding implementation


details from the user while exposing only the essential functionality.

▪ In other words, the user will have the information on what the object does instead of how it
does it.

▪ Use the abstract keyword to declare a class as abstract.

▪ The keyword appears in the class declaration somewhere before the class keyword.

▪ These classes cannot be used to instantiate objects, because, as we’ll soon see, abstract classes are
incomplete.
23
POLYMORPHISM

➢ Polymorphism is the ability of an object to take on many forms.

➢ Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.

➢ The most common use of polymorphism in OOP occurs when a parent class
reference is used to refer to a child class object.

➢ Inheritance lets us inherit attributes and methods from another class.


Polymorphism uses those methods to perform different tasks. This allows
us to perform a single action in different ways.

24
POLYMORPHISM example

➢ Think of a superclass called Animal that has a method called animalSound().

➢ Subclasses of Animals could be Pigs, Cats, Dogs, Birds

➢ And they also have their own implementation of an animal sound (the pig
oinks, and the cat meows, etc.):

25
HISTORY OF JAVA

• Developed by Sun Microsystems and released in 1995.

• Initiated by James Gosling and his team in 1991 as a project called "Oak". It was later renamed
to "Java" in 1995 as a core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).

• Multiple configurations were built to suit various types of platforms. For example, J2EE was built for
Enterprise Applications, and J2ME was built for Mobile Applications.

• Sun Microsystems has renamed the new J2 versions as Java SE (Standard Edition), Java EE
(Enterprise Edition), and Java ME (Micro Edition) respectively.
▪ Java was designed with portability and platform independence in mind, leading
to its famous slogan: "Write Once, Run Anywhere" (WORA) – Java programs
can run on any system with a compatible Java Virtual Machine (JVM).
• On 13 November 2006, Sun Microsystems released much of Java as free and open-source
software under the terms of the GNU General Public License (GPL). 26
FEATURES OF JAVA

➢ Object Oriented programming language : Which means that everything in


Java is an object. This makes it easier to model complex systems and reuse code, as
objects can be created, manipulated, and reused across different parts of a program.

➢ Platform independent: When Java code is compiled, it is not compiled into


platform-specific machine code. Instead, it is compiled into platform-independent
bytecode, which can be executed on any platform. This makes Java highly portable, as
a single Java program can be written and run on multiple platforms, such as Windows,
Mac, or Linux, without any changes to the code.

➢ Simple: If you understand the basic concept of OOP Java would be easy to master.
27
FEATURES OF JAVA

➢ Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.

➢ Robust: Java is designed to be a robust language that eliminates many common


programming errors by emphasizing compile-time error checking and runtime
checking. This makes it less likely for programs to crash or encounter runtime errors.
Additionally, Java has built-in garbage collection, which automatically frees up
memory that is no longer being used by a program. This helps prevent memory leaks
and other types of memory-related errors.

➢ Multithreaded: Java's multithreading feature allows developers to write programs that


can perform multiple tasks simultaneously. This can help improve performance
and responsiveness in certain types of applications, such as web servers or video games.28
JAVA FACTS

• Java is a popular programming language used for developing a wide range of


applications, from enterprise systems to consumer devices.

• Sun Microsystems, the original developer of Java, was acquired by Oracle in 2009.

• In 2010, Oracle announced that Java was running on 97% of enterprise desktops,
three billion handsets, and 80 million television devices.

• As of 2021, there are over 9 million Java developers worldwide.

• While the popularity of programming languages may vary, Java remains a widely used
language in the software development industry.
29
PHASES OF CREATING AND EXECUTING A JAVA APPLIC ATION

Java programs normally go through five phases. We discuss these phases in the context
of the Java SE Development Kit (JDK).

Edit Compile Load Verify Execute

30
PHASE 1 EDIT(WRITING THE CODE)

▪ In this phase, developers use a text editor or an Integrated Development


Environment (IDE) to write the Java source code.

▪ The source code is typically saved in a file with a .java extension. This file contains the
human-readable Java code that defines the program's logic and behaviour.

// Filename: HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

31
PHASE 2: COMPILE

• After writing the Java code, the next step is to compile it. The Java compiler (javac
command) translates the source code into an intermediate form called bytecode
which is saved in a file with a .class extension.
• Bytecode is a set of instructions that is platform-independent and can be executed
on any device with a Java Virtual Machine (JVM) installed.
• The bytecode is platform-independent, meaning it can be run on any device with a
JVM installed.

32
JAVA VIRTUAL MACHINE (JVM)

• The Java source code is compiled by the Java compiler into bytecodes that
define the tasks to be performed during the execution phase (Phase 5).

• These bytecodes are executed by the Java Virtual Machine (JVM), which is an
integral part of the JDK and serves as the foundation of the Java platform.

33
JAVA VIRTUAL MACHINE (JVM)

• A virtual machine (VM) is a software program that emulates a computer and


provides a platform for executing applications.

• The JVM, specifically, simulates the operation of a computer, while hiding the
underlying operating system and hardware from the programs that interact with it.

• Bytecodes, unlike machine language, are not dependent on specific computer


hardware and are platform-independent. This means that the same set of
bytecodes can be executed on any platform that has a JVM that understands the
version of Java.

• As a result, Java's bytecodes are portable, and you can execute them without
having to recompile the source code. 34
➢ To invoke the JVM, you can use the java command followed by the name of the
Java application you want to execute.

➢ For example, if you want to run a Java application named "Welcome," you would
type:

> java Welcome


➢ in a command window to invoke the JVM, which would then initiate the steps
necessary to execute the application. This begins Phase 3.

35
PHASE 3: LOADING A PROGRAM INTO MEMORY

➢ In Phase 3, the JVM places the program in memory to execute it—this is known as
loading.

➢ The JVM’s class loader takes the .class files containing the program’s bytecodes
and transfers them to primary memory.

➢ The class loader also loads any of the .class files provided by Java that your
program uses. The .class files can be loaded from a disk on your system or over a
network

36
37
PHASE 4: BYTECODE VERIFIC ATION

➢ In Phase 4, as the classes are loaded, the bytecode verifier examines their
bytecodes to ensure that they’re valid and do not violate Java’s security
restrictions .
➢ Java enforces strong security to make sure that Java programs arriving over the
network do not damage your files or your system (as computer viruses and worms
might)

38
PHASE 5: EXECUTION

➢ In Phase 5, the JVM executes the program’s bytecodes, thus performing the
actions specified by the program.

➢ In early Java versions, the JVM was simply an interpreter for Java bytecodes.

➢ This caused most Java programs to execute slowly, because the JVM would interpret
and execute one bytecode at a time.

➢ Today’s JVMs typically execute bytecodes using a combination of interpretation and


so-called just-in-time (JIT) compilation.

➢ In this process, the JVM analyses the bytecodes as they’re interpreted, searching for
hot spots (parts of the bytecodes that execute frequently).
39
➢ For these parts, a just-in-time (JIT) compiler—known as the Java HotSpot
compiler—translates the bytecodes into the underlying computer’s machine
language.
➢ When the JVM encounters these compiled parts again, the faster machine-language
code executes.

40
➢Thus Java programs actually go through two translation phases

➢ One in which source code is translated into bytecodes (for portability across JVMs
on different computer platforms)

➢ Second in which, during execution, the bytecodes are translated into


machine language for the actual computer on which the program executes.

41
MY FIRST JAVA APPLICATION
1st Line: public class HelloWorld
• Java is a true object-oriented language and therefor, Everything must be placed
inside a class
• ‘class’ is a keyword and declares a new class definition follows by the name –
HelloWorld
• The class uses an access specifier ‘public’, which indicates that our class is
accessible from other packages(packages are collection of classes)
2nd Line: {
• Every class definition in Java begins
with Opening curly brace ‘{‘ and
ends with a matching closing brace ‘}’
• We can place ‘{‘ next to the first line
• E.g. public class HelloWorld {

42
3rd Line: public static void main (String[] args)
• Indicates a method called ‘main’ in our class. The ‘main’ method is the starting
point of a Java program. It is where JVM begins execution of the program.
• A java application can have any number of classes but only one of them must
include a main method to initiate the execution.
• “public” : is an access specifier that says the “main” method is accessible to any
object (or to all classes)
• “static” : declares this method does not belong to an instance of a class, rather it
belongs to the class as a whole. “main” must always be declared “static” since the
interpreter uses this method before any objects are created.
• “void” : indicates main method does not return any value
• “String[] args” : declares parameter named args which contains an array of
strings. Array of strings is passed by command line.
NB: main method must always follow the above signature 43
• 5th Lne: System.out.println(“Hello World!”);
• Since Java is a true Object-Oriented language, every method must be part of an object. The
“println” method is a member of the out object, which is static data member of the
“System” class.
• Prints a given text to the screen.
• “println” appends a newlne to the end of string, “print” does not.
• Every Java program consists of at least one class declaration that is defined by the programmer.
• By convention all class names in Java begin with capitalized first letters of each word in a name.
• Class name can contain: digits, letters, underscore, dollar sign but do not begin with a digit.
• Java is CASE SENSETIVE!
• When we save a public class declaration in a file, the file name must be “class name” followed by
“.java” extension.
• Every Java statement must end with a semicolon.
44
COMMENTING YOUR PROGRAMS

➢ Comments used to increase the readability of document programs.


➢ Java compiler ignores comments , so they do not cause the computer to perform
any action when the program is run.
➢ There are two types of comments in Java
I. Single line comment begins with //, indicating that it is an end-of-line
comment- it terminates at the end of the line on which the // appears.
II. Traditional comments (multiline comments):- which can spread over several
lines
➢ These begin and end with delimiters /* and */

➢Forgetting one of the delimiters of a traditional or Javadoc comment is a syntax error.

45
➢ A syntax error occurs when the compiler encounters code that violates Java’s
language rules (i.e., its syntax)

➢ These rules are similar to a natural language’s grammar rules specifying sentence
structure.

➢ Syntax errors are also called compiler errors, compile-time errors or compilation
errors, because the compiler detects them during the compilation phase.

➢ The compiler responds by issuing an error message and preventing your program
from compiling.

46
DECLARING A CLASS

➢ The Phrase “public class FirstJavaCode “begins a class declaration

➢ Every Java program consists of at least one class that you (the programmer) define.

➢ The class keyword introduces a class declaration and is immediately followed by


the class name (HelloWorld).

➢ Keywords (sometimes called reserved words) are reserved for use by Java and
are always spelled with all lowercase letters.

47
DECLARING A METHOD

➢ public static void main( String[] args ) is the starting point of every Java application.

➢ The parentheses after the identifier main indicate that it’s a program building
block called a method. Java class declarations normally contain one or more
methods.

➢ For a Java application, one of the methods must be called main.

➢ Methods perform tasks and can return information when they complete their tasks.

➢ Keyword void indicates that this method will not return any information.

➢ the String[] args in parentheses is a required part of the method main’s declaration
48
PERFORMING OUTPUT WITH SYSTEM.OUT.PRINTLN

➢ System.out.println( “Hello World!" ); instructs the computer to perform an action—namely,


to print the string of characters contained between the double quotation marks (but not
the quotation marks themselves).

➢ A string is sometimes called a character string or a string literal.

➢ White-space characters in strings are not ignored by the compiler.

➢ The System.out object is known as the standard output object. It allows a Java
applications to display information in the command window from which it executes.

➢ Method System.out.println displays (or prints) a line of text in the command window.

➢ The string in the parentheses is the argument to the method.


49
COMPILING AND EXECUTING YOUR FIRST J AVA APPLIC ATION

▪ Using the Java Development Kit’s command-line tools, not an IDE.

▪ let's assume we have a folder in drive C : called “java”

50
public class EndOfChapter1 {

public static void main(String [] args){

System.out.println(“End of Chapter One. Thank you”) ;


System.out.println(“Reading Assignment- study about variables and data types in java”) ;

}
}

51
END OF CHAPTER 1

52

You might also like