[go: up one dir, main page]

0% found this document useful (0 votes)
8 views48 pages

Java_Chapter-1 (3)

This document provides an introduction to Object-Oriented Programming (OOP) in Java, covering fundamental concepts such as programming paradigms, the principles of OOP, and the structure of Java programs. It explains the differences between various programming styles, including imperative, procedural, functional, declarative, and object-oriented programming. Additionally, it outlines the steps for setting up a Java development environment and executing Java applications.

Uploaded by

gemechisgadisa77
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)
8 views48 pages

Java_Chapter-1 (3)

This document provides an introduction to Object-Oriented Programming (OOP) in Java, covering fundamental concepts such as programming paradigms, the principles of OOP, and the structure of Java programs. It explains the differences between various programming styles, including imperative, procedural, functional, declarative, and object-oriented programming. Additionally, it outlines the steps for setting up a Java development environment and executing Java applications.

Uploaded by

gemechisgadisa77
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/ 48

Jimma Institute of Technology

Faculty of Informatics and Computing

Program: Information Technology

Course Title: Object Oriented Programming in Java


Chapter 1
Introduction to Object-Oriented Programming

Compiled by Ermiyas T.
Objective

After completing this chapter you will be able to

• Identify common computer programming paradigms.

• Understand basic object oriented programming concepts.

• Understand Java programming types of Java applications

• Demonstrate and setting up Java development environment.

• Recognize and identify how Java code get compiled and executed.
Overview of Programming Language

What is Computer program?

• You use word processors to write documents, Web browsers to explore the
Internet, and email programs to send email.

– These are all examples of software that runs on computers.

• But, this software's are developed using programming languages.

• There are many programming languages — so why Java?

• The answer is that Java enables users to develop and deploy applications on the
Internet for servers, desktop computers, and small hand-held devices.
Types of Programming Paradigms
What is Programming Paradigms

• Programming paradigms are different ways or style in which a given


program or programming language can be organized.

• Each paradigm consists of certain structures, features, and opinions


about how common programming problem should be tackled.

Most common programming paradigms


• Imperative programming

• Procedural programming

• Functional programming

• Declarative programming

• Object-Oriented programming

• Event-Driven programming
Programming paradigms …

Imperative programming

• Is consists of a set of detailed instruction that are given to the computer


to execute in a given order.

• It's called "imperative" because as programmers we dictate exactly what


the computer has to do (how to do), in a very specific way.

• Say you want to bake a cake. Your imperative program to do this might
look like this: 1- Pour flour in a bowl
2- Pour a couple eggs in the same bowl
3- Pour some milk in the same bowl
4- Mix the ingredients
5- Pour the mix in a mold
6- Cook for 35 minutes
7- Let chill
Programming paradigms …

Imperative programming

• Using an actual (real-world) code example, let's say we want to filter an


array of numbers to only keep the elements bigger than 5.

• Our imperative code might look like this:


const nums = [1,4,3,6,7,8,9,2]
const result = [] // External variable

for (let i = 0; i < nums.length; i++) {


if (nums[i] > 5)
result.push(nums[i])
}
console.log(result) // Output: [ 6, 7, 8, 9 ]

• We're being detailed and specific in our instructions, and that's what
imperative programming stands for.
Programming paradigms …

Procedural programming function pourIngredients() {


- Pour flour in a bowl
• Is a derivation of imperative - Pour a couple eggs in the same bowl
programming, adding to it the - Pour some milk in the same bowl
feature of functions (also known as }
"procedures" or "subroutines"). function mixAndTransferToMold() {
- Mix the ingredients
• The user is encouraged to subdivide
- Pour the mix in a mold
the program execution into }
functions, as a way of improving function cookAndLetChill() {
modularity and organization. - Cook for 35 minutes
- Let chill
• Following our cake example,
}
procedural programming may look
pourIngredients()
like this:
mixAndTransferToMold()
cookAndLetChill()
Programming paradigms …
Functional Programming

• Functional programming takes the concept of functions a little bit further.

• In this approach, functions are treated as first-class citizens, meaning


that they can be assigned to variables, passed as arguments, and
returned from other functions.

• Another key concept is the idea of pure functions.

• A pure function is one that relies only on its inputs to generate its result.

• Given the same input, it will always produce the same result. Besides, it
produces no side effects (any change outside the function's
environment).

• With these concepts in mind, functional programming encourages


programs written mostly with functions (surprise 😲).
Cont …

• To transform the previous imperative programming into functional


programming, we could do it like this:
const nums = [1,4,3,6,7,8,9,2]

function filterNums() {
const result = [] // Internal variable

for (let i = 0; i < nums.length; i++)


if (nums[i] > 5) result.push(nums[i])
return result
}
console.log(filterNums()) // Output: [ 6, 7, 8, 9 ]

• It's almost the same code, but we wrap our iteration within a function, in
which we also store the result array.
• In this way, we can assure the function doesn't modify anything outside
its scope. It only creates a variable to process its own information, and
once the execution is finished, the variable is gone too.
Programming paradigms …

Declarative Programming

• Declarative programming is all about hiding away complexity and


bringing programming languages closer to human language and thinking.

• Direct opposite of imperative programming in the sense that the


programmer doesn't give instructions about how the computer should
execute the task, but rather on what result is needed.
const nums = [1,4,3,6,7,8,9,2]
console.log(nums.filter(num => num > 5)) // Output: [ 6, 7, 8, 9 ]

• See that with the filter function, we're not explicitly telling the computer to
iterate over the array or store the values in a separate array.

• An important thing to notice about declarative programming is that under


the hood, the computer processes this information as imperative code
anyway.
Programming paradigms …

Object-Oriented Programming

• The core concept of OOP is to separate concerns into entities which are
coded as objects. Each entity will group a given set of information
(properties) and actions (methods) that can be performed by the entity.

• Object-orientation provides a new view of computation.

– A software system is seen as a community of objects that cooperate


with each other by passing messages in solving a problem.
Which style is better?

• Which programming paradigm is best?

– The answer for this question is it depends on the problem you are
trying to solve.

• Problem Solving: is a process of defining a problem, identifying and


comparing different solutions, and picking the one that best solves that
problem with respect to the context and constraints.

• Some people claim using object oriented programming is often a better


choice for creating a GUIs and Games.

• On the other hand, Functional programming makes more seance for


application that require hinger level of reliability or problems that involve
messages been passed around and getting transformed.

• No paradigm is best in all situations.


Object Oriented Principles.
Pillars of Object-Oriented Programming

• An object-oriented programming language provides support for the


following object-oriented concepts:
Why is OOP?

• Before object oriented programming, we had procedural programming


that divided a program into multiple functions.
• Ex. We are going to create a video game.
– While creating a video game we would need to create a plater object
(this is the one that going to hold the data of our players) like:
const player = {
name: “Bill Gate”,
health: 85,
skill: “Programmer”
};
– Creating players like this is okay when we only have to create one
player, and the problem is happens when this number starts to grow.
const player = { const player = {
name: “Bill Gate”, name: “Elon Mask”,
health: 85, health: 60,
skill: “Programmer” skill: “Entrepreneur”
}; };
const player = {
name: “Sir Dar”,
health: 90,
skill: “Business”
};
Cont …

• What is a problem with procedural programming?


– Mistake when we are creating a player and we might forget to add
some attribute to one player or we might misspell a property.
– An other problem is that adding a new property for the player is
difficult. We have to search all players and add new property.
• Therefore, the good idea is to create some player factory.
– Object oriented programming is a best solution for this problem.
– For example, if you want to modify the code by adding a new property
to each player, you only edit a single unit (i.e. player factory).
class Player {
constructor(name, health skill) {
this.name = name;
this.health = health;
this.skill = skill;
};
Other example of Class and Object

• Question: what’s data and behaviors a TV have?


Cont …

Classe
• A class is a blueprint that defines the variables and the methods common
to all objects of a certain kind.
• The class declares the instance variables necessary to contain the state
of every object.
• After you’ve created the class, you can create any number of objects
from that class.

Object
• An object is a software bundle of variables and related methods.
• An object is also known as an instance. An instance refers to a particular
object.
• The variables of an object are formally known as instance variables
because they contain the state for a particular object or instance.
Class vs Object

Critical difference between Class and Object?

• No memory is allocated when a class is created. Memory allocation


happens only when the actual instances of a class(the objects) are
created.
4 Pillars of Object-Oriented Principle

• Encapsulation:

• Encapsulation is the first principle of object-oriented programming.

• It suggests that we should bundle the data and operations on the data
inside a single unit (class).

• Abstraction

• It suggests that we should reduce complexity by hiding the


unnecessary implementation details.

• As a metaphor, think of the remote control of your TV. All the complexity
inside the remote control is hidden from you. It’s abstracted away. You
just work with a simple interface to control your TV. We want our objects
to be like our remote controls.
4 Pillars of Object-Oriented Principle

Inheritance:

• Encapsulation is a mechanism for reusing code.


• The process by which objects of one class acquire the properties of
objects of another class..

Polymorphism

• a mechanism that allows an object to take many forms and behave


differently. This will help us build extensible applications.

• Plays an important role in allowing objects having different internal


structures to share the same external interface.

– Overloading methods
– Overriding methods, and
– Dynamic method binding
• Overloaded methods: methods with the same name signature but either
a different number of parameters or different types in the parameter list.

• Overridden methods: are methods that are redefined within an inherited


or subclass. They have the same signature and the subclass definition is
used.

• Dynamic binding: means that the code associated with a given


procedure call is not known until the time of the call at runtime. Memory is
allocated at runtime not at compilation time.
Java Programming and types of Java Program
Overview of Java Programming

Interesting facts about Java

• Java wase developed by James Gosling in 1995 at sun microsystem


which was purchased by Oracle in 2010.

• It was originally called oak, after an oak tree that stood outside Gosling’s
office. Later, it was renamed to green, and was finally renamed to Java,
inspired by Java coffee.

• It’s a general purpose & powerful programming language.

• Used for developing software that run on mobile, desktop, and servers.

• Machin Independence.
Overview of Java Programming

Java API

• Application programming interface a.k.a. library.


• Contains predefined Java code that we can use to develop
Java programs.

Editions of Java

• We have four edition of Java for building different type of applications.

– Standard Edition: used to develop client-side standalone


applications or applets.
– Enterprise Edition: used to develop server-side applications such as
Java servlets, Java ServerPages, and Java ServerFaces.
– Micro/Mobile Edition: develop applications for mobile devices.
• Java is different from other programming languages because a Java
program is both compiled and interpreted but in many other languages,
the program is either compiled or interpreted.

• The Java language is object-oriented and programs written in Java are


portable – that is, they can be run on many different platforms (e.g.
Windows, Mac, Linux, Solaris).

• The Java compiler translates the program into an intermediate language


called Java bytecodes.

• Java bytecodes are platform-independent – this means they can be run


on different operating systems.

• There are different Java interpreters for different platforms. The


interpreter parses and runs each of the Java bytecode instructions.
Your First Java Program

A Simple Java Program

• Every Java program must have at least one class. Each class has a
name. By convention, class names start with an uppercase letter.

• In a program, multiple classes may cooperate with each other.

• Each program needs an entry point to start execution.

• The program is executed from the main method that is defined in one of
the classes. A class may contain several methods. The main method is
the entry point where the program begins execution.
Steps for running a Java program

• There are five steps to execute Java application.

1. Create (Write): consists of editing a file with an editor program.

• Java source code files are saved with .java extension.

2. Compile: using a command javac we can compile source code to


bytecode.

• Syntax: javac ClassName.java

3. Load: JVM places the program (ClassName.class) in memory to


execute it – this is known as loading.

• Syntax: java ClassName

4. Verify: during the loading process java will check for restrictions.

5. Execute: the CPU will execute the machine code.


Compiling and Interpreting in Java

• The Java language is a high-level language, but Java bytecode is a low-


level language.

• The bytecode is similar to machine instructions but is architecture neutral


and can run on any platform that has a Java Virtual Machine (JVM).

• The virtual machine is a program that interprets Java bytecode. This is


one of Java’s primary advantage.

• Java source code is compiled into Java bytecode (.class file) and Java
bytecode is interpreted by the JVM. Your Java code may use the code in
the Java library. To execute a Java program is to run the program’s
bytecode.
Java Software Requirment

• Java Development Kit(JDK) contains

– existing Java libraries data

– Compilers and Java Virtual Machines

• Integrated Development Environment(IDE) contains editors &


debuggers(for locating)

– e.g. Notepad, Eclipse, NetBeans, IntelliJ …


What is Java Applet?

• Individual Assignment 1.

– What is Java Applet?

– What is Java application?

– What is the difference between Applet and application?

– Write and compile a real world example of applet?

– Submission date November 9, 2023


Anatomy of Java Program

• Class name • Every Java program must have at least one


class. Each class has a name.
• Main method
• By convention, class names start with an
• Statements
uppercase letter. In this example, the class
• Statement terminator name is Welcome.

• Reserved words

• Comments
// This program prints Welcome to Java!
• Blocks public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Anatomy of Java Program

• Class name • Line 2 defines the main method. In order to run


a class, the class must contain a method
• Main method
named main.
• Statements
• The program is executed from the main
• Statement terminator method..

• Reserved words

• Comments
// This program prints Welcome to Java!
• Blocks public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Anatomy of Java Program

• Class name • A statement represents an action or a


sequence of actions.
• Main method
• The statement System.out.println("Welcome to
• Statements
Java!") in the program below is a statement to
• Statement terminator display the greeting "Welcome to Java!”.

• Reserved words

• Comments
// This program prints Welcome to Java!
• Blocks public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Anatomy of Java Program

• Class name • Reserved words or keywords are words that


have a specific meaning to the compiler and
• Main method
cannot be used for other purposes in the
• Statements program.

• Statement terminator • For example, when the compiler sees the word
class, it understands that the word after class is
• Reserved words
the name for the class.
• Comments
// This program prints Welcome to Java!
• Blocks public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Java Package

What is Java Packages?

• Java applications which users write are made up of classes.

• When the number of classes grows, it tends to be difficult to manage.

• To solve this, Java allows developers to organize the classes in Java


applications using packages.

• A package in Java is used to group related classes.

• Think of it as a folder in a file directory.

• We use packages to avoid name conflicts, and to write a better


maintainable code.
How to create Java Packages?

• To create a package simply includes a package command as the first


statement in a Java source file.

– package packageName;

• Any classes declared within that file will belong to the specified package.
• Java uses file system directories to store packages.
• For example, the .class files for any classes you declare to be part of
packageName must be stored in a directory called packageName.
• Remember that case-sensitive, and the directory name must match the
package name exactly.
• Packages are divided into two categories:
– Built-in Packages (packages from the Java API)
– User-defined Packages (create your own packages)
Cont…

Built-in Packages

• The Java API is a library of prewritten classes that are free to use,
included in the Java Development Environment (JDE).

• The library contains components for managing input, database


programming, and much more.

• The library is divided into packages and classes. Meaning:

– Either import a single class (along with its methods and attributes), or
– The whole package that contain all the classes that belong to the
specified package.

• To use a class or a package from the library, you need to use


the import keyword.
Cont…

Built-in Packages …
• You can include as many import statements as are necessary to import
all the classes used by your program.
• This is the general form of the import statement:
– import pkg1.pkg2.Classname; // Import a single class
– import pkg1.pkg2.*; // Import the whole package
• Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).
• Example:
– import java.util.Scanner;
– import java.io.*;
Cont …

Java User Input using built-in package and class (Scanner)

• The Scanner class is used to get user input, and it is found in


the java.util package.
• To use the Scanner class, create an object of the class and use any of
the available methods found In the Scanner class documentation.
Method
import java.util.Scanner; // Import the Scanner class
nextBoolean()

public class MyClass { nextByte()


public static void main (String[] args) { nextDouble()
Scanner myObj = new Scanner(System.in); nextFloat()
System.out.println(“Enter Your Name: ”);
nextInt()
String userName = myObj.nextLine();
System.out.println("Username is: " + nextLine()
userName); nextLong()
}
nextShort()
}
Cont …

User-defined Packages

• To create your own package, you need to understand that Java uses a
file system directory to store them.

• To create a package, use the package keyword:

• Example: MyPackageClass.java
package mypack;

public class MyPackageClass {


public static void main (String[] args) {
System.out.println(“This is my package.”)
}
}
• 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.
Programming Style and Documentation

• Appropriate Comments

• Naming Conventions

• Proper Indentation and Spacing Lines

• Block Styles

• Programming Errors

– Syntax Errors
• Detected by the compiler
– Runtime Errors
• Causes the program to abort
– Logic Errors
• Produces incorrect result
Java Application and Applet/Servlet

• Java is categorized as Application and Applet/Servlet

– Java Applications: Standalone Programs(run standalone)

– Java Applets: do not run standalone, adhere a set of conventions


that lets them run in java compatible browsers

– Java Servlets: java on the server side

You might also like