COMP1Lp1 (1)
COMP1Lp1 (1)
1.1 INTRODUCTION
OOPS is about developing an application around its data, i.e. objects which provides
the access to their properties and the possible operations in their own way. These
features include Abstraction, encapsulation, inheritance and polymorphism.
ABSTRACTION
ENCAPSULATION
Encapsulation is a) Binding the data with the code that manipulates it. B) It keeps the
data and the code safe from external interference
C. M. D. Hamo-ay
1 | Computer Programming 2
car is a complex system, which internally have lots of components tightly coupled
together, they work synchronously to turn the car in the desired direction. It even
controls the power delivered by the engine to the steering wheel. But to the external
world there is only one interface is available and rest of the complexity is hidden.
Moreover, the steering unit in itself is complete and independent. It does not affect
the functioning of any other mechanism.
INHERITANCE
POLYMORPHISM
Polymorphism is one of the OOPs feature that allows us to perform a single action in
different ways. For example, let’s say we have a class Animal that has a
method sound (). Since this is a generic class so we can’t give it an implementation
like: Roar, Meow, Oink etc. We had to give a generic message. In OOP using Java we
can write it this way,
C. M. D. Hamo-ay
1 | Computer Programming 3
Syntax
class <class_name>{
field;
method;
}
Ops! Don’t worry about the syntax for now, you will learn it later.
From a programming point of view, an object in OOPS can include a data structure,
a variable, or a function. It has a memory location allocated. Java Objects are
designed as class hierarchies.
Syntax
C. M. D. Hamo-ay
1 | Computer Programming 4
An object in OOPS is a specimen of a class. Software objects are often used to model
real-world objects you find in everyday life
Let’s take an example of developing a pet management system, specially meant for
dogs. We need various information about the dogs like different breeds of the dogs,
the age, size, etc.
You need to model real-life beings, i.e., dogs into software entities let’s have an
illustration,
Solution:
C. M. D. Hamo-ay
1 | Computer Programming 5
Step 2: Next, list out the common behaviors of these dogs like sleep, sit, eat,
etc. So these will be the actions of our software objects.
C. M. D. Hamo-ay
1 | Computer Programming 6
Class – Dogs
Data members or objects– size, age, color, breed, etc.
Methods– eat, sleep, sit and run.
For better understanding we can model the Dog according to the diagram below,
Step 4: Now, for different values of data members (breed size, age, and color)
in Java class, you will get different dog objects.
Step 5: You can design any program using this OOPs approach.
C. M. D. Hamo-ay
1 | Computer Programming 7
Single Responsibility Principle (SRP)- A class should have only one reason to
change
Open Closed Responsibility (OCP)- It should be able to extend any classes
without modifying it
Liskov Substitution Responsibility (LSR)- Derived classes must be substitutable
for their base classes
Dependency Inversion Principle (DIP)- Depend on abstraction and not on
concretions
Interface Segregation Principle (ISP)- Prepare fine grained interfaces that are
client specific
Example 1-2 Let us now examine the java program of the given dog information
// Class Declaration
public class Dog {
// Instance Variables
String breed;
String size;
int age;
String color;
// method 1
public String getInfo() {
return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is:
"+color);
}
C. M. D. Hamo-ay
1 | Computer Programming 8
Well, the code is quite complicated for now however, we follow the correct
algorithm construction of java program. Don’t worry my dear you will be
enlightened in the coming lessons.
Breed is: Maltese Size is: Small Age is:2 color is: white
In previous program, we are creating main() method inside the class. Now, we
create classes and define main() method in another class. This is a better way than
previous one.
// Class Declaration
class Dog {
// Instance Variables
String breed;
String size;
int age;
String color;
// method 1
public String getInfo() {
return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is: "+color);
}
}
public class Execute{
public static void main(String[] args) {
Dog maltese = new Dog();
maltese.breed="Maltese";
maltese.size="Small";
maltese.age=2;
maltese.color="white";
System.out.println(maltese.getInfo());
}
}
C. M. D. Hamo-ay
1 | Computer Programming 9
Breed is: Maltese Size is:Small Age is:2 color is: white
Summary
Java Class is an entity that determines how java objects will behave and what
objects will contain
A Java objects is self-contained component which consists of methods and
properties to make certain type of data useful
A class system allows the program to define a new class(derived class) in
terms of an existing class(super class) by using a technique like inheritance,
overriding and augmenting.
UML or Unified Modelling Language is the symbol used to explain the purpose of
the four most common diagrams this are: Class, Object, sequence, and package
diagrams. These diagrams are used extensively when describing software designed
according to Object Oriented programming approach.
Our objective here is to draw a class diagram, object diagram, sequence diagram,
and package diagrams. We need also to understand the different class relationships,
Association, dependency Inheritance and implementation. Let’s have examples,
A Class in UML diagram is a blueprint used to create an object or set of objects. The
Class defines what an object can do. It is a template to create various objects and
implement their behavior in the system. A Class in UML is represented by a
rectangle that includes rows with class names, attributes, and operations.
C. M. D. Hamo-ay
1 | Computer Programming 10
Class Diagram Illustrates data models for even very complex information
systems
It provides an overview of how the application is structured before studying the
actual code. This can easily reduce the maintenance time
It helps for better understanding of general schematics of an application.
Allows drawing detailed charts which highlights code required to be
programmed
Helpful for developers and other stakeholders.
1. Class Name
2. Attributes
3. Operations
Class Name
C. M. D. Hamo-ay
1 | Computer Programming 11
Attributes:
A derived attribute is computed from other attributes. For example, an age of the
student can be easily computed from his/her birth date.
Attributes characteristics
Relationships
1. Dependencies
2. Generalizations
3. Associations
Dependency
A dependency means the relation between two or more classes in which a change in one
may force changes in the other. However, it will always create a weaker relationship.
C. M. D. Hamo-ay
1 | Computer Programming 12
In the following UML class diagram examples, Student has a dependency on College
Generalization:
Association:
This kind of relationship represents static relationships between classes A and B. For
example; an employee works for an organization. Here are some rules for Association:
In this example, the relationship between student and college is shown which is studies.
C. M. D. Hamo-ay
1 | Computer Programming 13
Multiplicity
Let’s say that that there are 100 students in one college. The college can have multiple
students.
Aggregation
For example, the class college is made up of one or more student. In aggregation, the
contained classes are never totally dependent on the lifecycle of the container. Here, the
college class will remain even if the student is not available.
Composition:
For example, if college is composed of classes student. The college could contain many
students, while each student belongs to only one college. So, if college is not functioning
all the students also removed.
C. M. D. Hamo-ay
1 | Computer Programming 14
Abstract Classes
It is a class with an operation prototype, but not the implementation. It is also possible
to have an abstract class with no operations declared inside of it. An abstract is useful
for identifying the functionalities across the classes. Let us consider an example of an
abstract class. Suppose we have an abstract class called as a motion with a method or an
operation declared inside of it. The method declared inside the abstract class is called
a move ().
This abstract class method can be used by any object such as a car, an animal, robot, etc.
for changing the current position. It is efficient to use this abstract class method with an
object because no implementation is provided for the given function. We can use it in
any way for multiple objects.
In UML, the abstract class has the same notation as that of the class. The only difference
between a class and an abstract class is that the class name is strictly written in an italic
font.
C. M. D. Hamo-ay
1 | Computer Programming 15
UML Class Diagram Creating a class diagram is a straightforward process. It does not
involve many technicalities.
ATMs system is very simple as customers need to press some buttons to receive cash.
However, there is multiple security layers that any ATM system needs to pass. This
helps to prevent fraud and provide cash or need details to banking customers.
C. M. D. Hamo-ay
1 | Computer Programming 16
Class diagrams are the most important UML diagrams used for software application
development. There are many properties which should be considered while drawing
a Class Diagram. They represent various aspects of a software application.
Here, are some points which should be kept in mind while drawing a class diagram:
The name given to the class diagram must be meaningful. Moreover, It should
describe the real aspect of the system.
The relationship between each element needs to be identified in advance.
The responsibility for every class needs to be identified.
For every class, minimum number of properties should be specified. Therefore,
unwanted properties can easily make the diagram complicated.
User notes should be included whenever you need to define some aspect of the
diagram. At the end of the drawing, it must be understandable for the software
development team.
Lastly, before creating the final version, the diagram needs to be drawn on plain
paper. Moreover, It should be reworked until it is ready for final submission.
C. M. D. Hamo-ay
1 | Computer Programming 17
1. 4 References
1. https://www.guru99.com/uml-class-diagram.html
2. https://www.guru99.com/java-oops-class-objects.html
3. Simon Kendal Object oriented programming using C#, 2nd Edition, 2018,
4. Stuart Reges ,Marty Stepp. Building Java Program. 2011, Pearson Education, Inc.,
publishing as Addison-Wesley.
C. M. D. Hamo-ay
1 | Computer Programming 18
2.1 INTRODUCTION
Programming is an art of science of reasoning .Why?, just because when you create
your program later on you are already considered a programmer isn’t it?
Programmers spent months years to develop such passionate work however, you
and them must deserve loved , recognition and above all understanding. Before we
proceed with creating a program let us be familiarize ourselves with the important
terminologies that we are going to use in our discussion.
This is generally referred as JVM. Before, we discuss about JVM lets see the phases of
program execution. Phases are as follows: we write the program, then we compile
the program and at last we run the program.
1) Writing of the program is of course done by java programmer like you and me.
3) In third phase, JVM executes the byte code generated by compiler. This is called
program run phase.
So, now that we understood that the primary function of JVM is to execute the byte
code produced by compiler. Each operating system has different JVM; however the
output they produce after execution of byte code is same across all operating
systems. That is why we call java as platform independent language.
C. M. D. Hamo-ay
1 | Computer Programming 19
BYTECODE
As discussed above, javac compiler of JDK compiles the java source code into byte
code so that it can be executed by JVM. The byte code is saved in a .class file by
compiler.
While explaining JVM and bytecode, I have used the term JDK. Let’s discuss about
it. As the name suggests this is complete java development kit that includes JRE
(Java Runtime Environment), compilers and various tools like JavaDoc, Java
debugger etc. In order to create, compile and run Java program you would need JDK
installed on your computer.
JRE is a part of JDK which means that JDK includes JRE. When you have JRE
installed on your system, you can run a java program however you won’t be able to
compile it. JRE includes JVM, browser plugins and applets support. When you only
need to run a java program on your computer, you would only need JRE.
Java Virtual Machine (JVM), Difference JDK, JRE & JVM – Core Java
Java Virtual Machine (JVM) is a virtual machine that resides in the real machine
(your computer) and the machine language for JVM is byte code. This makes it
easier for compiler as it has to generate byte code for JVM rather than different
machine code for each type of machine. JVM executes the byte code generated by
compiler and produce output. JVM is the one that makes java platform independent.
So, now we understood that the primary function of JVM is to execute the byte code
produced by compiler. Each operating system has different JVM, however the
output they produce after execution of byte code is same across all operating
systems. Which means that the byte code generated on Windows can be run on Mac
OS and vice versa. That is why we call java as platform independent language. The
same thing can be seen in the diagram 1.1.
C. M. D. Hamo-ay
1 | Computer Programming 20
So to summarise everything: The Java Virtual machine (JVM) is the virtual machine
that runs on actual machine (your computer) and executes Java byte code. The JVM
doesn’t understand Java source code, that’s why we need to have javac compiler that
compiles *.java files to obtain *.class files that contain the byte codes understood by
the JVM. JVM makes java portable (write once, run anywhere). Each operating
system has different JVM, however the output they produce after execution of byte
code is same across all operating systems.
JVM Architecture
C. M. D. Hamo-ay
1 | Computer Programming 21
Functions:
Class Loader: The class loader reads the .class file and save the byte code in
the method area.
Method Area: There is only one method area in a JVM which is shared among all the
classes. This holds the class level information of each .class file.
Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a
Class object for each .class file.
Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing
temporary variables.
PC Registers: This keeps the track of which instruction has been executed and which
one is going to be executed. Since instructions are executed by threads, each thread
has a separate PC register.
Native Method stack: A native method can access the runtime data areas of the
virtual machine.
JRE: JRE is the environment within which the java virtual machine runs. JRE
contains Java virtual Machine (JVM), class libraries, and other files excluding
development tools such as compiler and debugger.
Which means you can run the code in JRE but you can’t develop and compile the
code in JRE.
JVM: As we discussed above, JVM runs the program by using class, libraries and
files provided by JRE.
C. M. D. Hamo-ay
1 | Computer Programming 22
JDK: JDK is a superset of JRE, it contains everything that JRE has along with
development tools such as compiler, debugger etc
Example 2.1 Create a java program that will produce an output “This is my
first program in java”
Solution:
C. M. D. Hamo-ay
1 | Computer Programming 23
Note: This program is quite complicated as of now. However, we can have better
understanding in the next discussion. Don’t worry be happy.
Prerequisite: You need to have java installed on your system. You can get the java
from here.
Step 1: Open a text editor, like Notepad on windows and TextEdit on Mac. Copy the
above program and paste it in the text editor.
Step 2: Save the file as FirstJavaProgram.java. You may be wondering why we have
named the file as FirstJavaProgram, the thing is that we should always name the file
same as the public class name. In our program, the public class name
is FirstJavaProgram, that’s why our file name should be FirstJavaProgram.java.
Step 3: In this step, we will compile the program. For this, open command prompt
(cmd) on Windows, if you are Mac OS then open Terminal.
To compile the program, type the following command and hit enter
javac FirstJavaProgram.java
If you get some error then you first need to set the path before compilation.
Open command prompt (cmd), go to the place where you have installed java on
your system and locate the bin directory, copy the complete path and write it in the
command like this.
Note: Your jdk version may be different. Since I have java version 1.8.0_121 installed
on my system, I mentioned the same while setting up the path.
Step 4: After compilation the .java file gets translated into the .class file(byte code).
Now we can run the program. To run the program, type the following command
C. M. D. Hamo-ay
1 | Computer Programming 24
java FirstJavaProgram
Now that we have understood how to run a java program, let have a closer look at
the program we have written above.
This is the first line of our java program. Every java application must have at least
one class definition that consists of class keyword followed by class name. When I
say keyword, it means that it should not be changed, we should use it as it is.
However the class name can be anything
This is our next line in the program, lets break it down to understand it:
public: This makes the main method public that means that we can call the method
from outside the class.
static: We do not need to create object for static methods to run. They can run itself.
main: It is the method name. This is the entry point method from which the JVM can
run your program.
(String[] args): Used for command line arguments that are passed as strings. We will
cover that in a separate post.
C. M. D. Hamo-ay
1 | Computer Programming 25
This method prints the contents inside the double quotes into the console and inserts
a newline after.
SAQ 2-1 Create a program that will produce the following output
Hello ECE 1!
Is these the first time here in SSU?
How is your first class in Programming 1?
Example 2.2 Compute the sum of two integers given that x = 1 and y = 5
Solution:
Step 1 : Identify the variables in the problem this are: x , and y, its so happen
that the value assigned on the variable x and y is given as 1, and 5
respectively that becomes a constant.
Step 2 : Upon knowing the given, what are you going to do with these
values? Yes! We are going to find the sum. So we can name another
variable who will hold the result when adding these two values, let us
use variable sum,
C. M. D. Hamo-ay
1 | Computer Programming 26
Step 3 : Create now the program algorithm using the java format mentioned
in our previous example we have,
Example 2.3 Modify example 2.2, these time you input two values of x and y instead
of constant.
Solution:
Remember in this problem we need Scanner so that our input will be recognize
Step 1 : Identify the variables, we can use the same variables: x,y,sum
Step 2 : Input the first integer assign the variable x
Input the second integer assign the variable y
Compute the sum of x + y
Display the result
Step 3 : Code the program
The Scanner allows us to capture the user input so that we can get the values of both
the numbers from user. The program then calculates the sum and displays it.
C. M. D. Hamo-ay
1 | Computer Programming 27
import java.util.Scanner;
public class AddTwoNumbers2 {
int x, y, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
x = sc.nextInt();
sc.close();
sum = x + y;
System.out.println("Sum of these numbers: "+sum);
}
}
One of the most common statement in programming is with the use of if..else
statement . These is a conditional statements that would allow to execute the
correctness of the statements in mathematics we use the symbol: >greater than, <less
than, = equal to, != not equal to , ║ or , && and ≥greater than or equal to, less than or
equal two≤, in these symbol we can check the validity of the given condition where
it is true or false. Le’s have a simple example.
C. M. D. Hamo-ay
1 | Computer Programming 28
Example 2.4 Input two integers display the largest among the two
Solution:
Step 1 : we have three variables again, x,y, and large, large variable will hold
the result after comparison.
Step2 : Create the algorithm
: Input the first integer and assign x to hold the value
: Input second integer and assign y to hold the value
: Compare the two integers and select which is the largest
: Display the result
Step3: : Code the program
C. M. D. Hamo-ay
1 | Computer Programming 29
import java.util.Scanner;
if(x>y)
{
large= x;
}
else
{
large = y;
}
2.5 LOOPS
The for loop helps to avoid such redundancy by repeatedly executing a sequence of
statements over a particular range of values.
C. M. D. Hamo-ay
1 | Computer Programming 30
Example 2.4 Suppose you want to write out the squares of the first five integers.
You could write a program like this:
C. M. D. Hamo-ay
1 | Computer Programming 31
To avoid these repetitive task manually instead, we use “ for” loop so we can write
in these way,
Condition: i<=5;
3 for (int i = 1; i <= 5; i++) {
Increment: i++
4 System.out.println(i + " squared = " + (i * i));
5}
6}
7}
Note: there are three loops in programming these are: do..while, while..do, and for.
C. M. D. Hamo-ay
1 | Computer Programming 32
Assignment No. 1
1. a) Discuss problems and issues regarding the following subject of concern and
b) Find each concrete solutions to the problems you have identified.
Abstraction
INCAPSULATION
INHERITANCE
POLYMORPHISM
2. A man deposited his money in the bank for a period of n years. How much
money does he have in the bank if he withdraws the amount after how many
years assuming the money initially invested has interest compounded
annually(assume 5% or less). Use variables in the problem just for the purpose
of exercises and use for loop in the solution.
C. M. D. Hamo-ay
1 | Computer Programming 33
2.6 References
1. https://beginnersbook.com/java-tutorial-for-beginners-with-examples/
2. Simon Kendal. Object oriented programming using C#, 2nd Edition, 2018,
4. Stuart Reges ,Marty Stepp. Building Java Program. 2011, Pearson Education, Inc.,
publishing as Addison-Wesley.
2.7 Acknowledgment
Further revealed that the images, tables, figures and information contained in this
module were taken from the references cited above.
C. M. D. Hamo-ay
1 | Computer Programming 34
C. M. D. Hamo-ay
1 | Computer Programming 35
C. M. D. Hamo-ay