E Book OOP
E Book OOP
1
List of figures
Figure 1 ........................................................................................................................................... 9
Figure 2 ............................................................................................ Error! Bookmark not defined.
Figure 3 ............................................................................................ Error! Bookmark not defined.
Figure 4 ............................................................................................ Error! Bookmark not defined.
Figure 5 ............................................................................................ Error! Bookmark not defined.
Figure 6 ............................................................................................ Error! Bookmark not defined.
Figure 7 ............................................................................................ Error! Bookmark not defined.
Figure 8 ............................................................................................ Error! Bookmark not defined.
Figure 9 ............................................................................................ Error! Bookmark not defined.
Figure 10 .......................................................................................... Error! Bookmark not defined.
Figure 11 .......................................................................................... Error! Bookmark not defined.
Figure 12 .......................................................................................... Error! Bookmark not defined.
2
List of Table
Table 1 .............................................................................................. Error! Bookmark not defined.
Table 2 ........................................................................................................................................... 13
Table 3 .............................................................................................. Error! Bookmark not defined.
Table 4 .............................................................................................. Error! Bookmark not defined.
3
LESSON 01 –LANGUAGE FUNDAMENTALS
1.1 Introduction
Java is high-level programming language which is developed by sun micro systems. It was
released on 1995. This runs on a variety of platforms such as Linux, Mac, Windows...etc.
The following are more important points on java.
• Object oriented.
• Platform independent.
• Portable.
• Secure.
• Architecture Neutral.
JRE
This provides the libraries, the Java Virtual Machine, and other components to run
java applications.
JDK
This is a superset of the JRE, and contains everything that is in the JRE, and tools
such as the compilers and debuggers necessary for developing java applications.
Virtual Machine
This provides runtime environment to execute java byte code. All language
compilers translate source code into machine code for specific computer. Java
compiler produces an intermediate code known as bytecode for a machine that
does not exist. This machine is called the java virtual machine and exits only
inside the computer memory. It is a simulated computer within the computer and
does all major functions of a real computer.
4
The virtual machine code is not machine specific. The machine specific code is
generated by the java interpreter by acting as intermediary between the virtual and
real machine.
Class SampleOne
{ public static void main (String args[])
{ System.out.printnln(“Java is better than C++”);
}
}
Class Declaration
Everything must be placed inside a class
E.g.: class SampleOne
Main Method
Every java program must include the main method. Starting point for the
interpreter to begin the execution of the program. Java application can have any
number of classes but only one of them must include main method to initiate the
execution.
public :
main method as unprotected and therefore making it accessible to all
other classes.
static :
Declare this method as one that belongs to the entire class and not a part of any
objects of the class.
void :
main method does not return any value.
5
Output Line:
Every method must be part of an object.
print method is a member of the out object, which is a static data member of
System class.
Concatenation
+ Acts as concatenation operator of two strings. Value of y converted into a string
representation before concatenation.
Comments
Single line comment //
Multiline comment /* */
Documentation
Comprises a set of comment lines giving the name of the program, author and
other details.
Package statement
Declares a package name and informs the compiler that the classes defined here
belong to this package.
E.g: package student
Import statements
Instruct interpreter to load the test class contained in the package student.
E.g.: import student.test;
Interface statements
New concept in java
Like a class but includes a group of method declarations.
Class definitions
A java may contain multiple class definitions.
Main Method Class
Every java stand –along program requires a main method as its starting point, this
class is essential part of a java program.
6
1.5 Compilation and Execution
The source code(.java) is converted to byte code (Machine Code) at the end of the compilation.it
created .class file for content of each class in the source code.
Once byte code is created, it can be interpreted and executed on java virtual machine.
Figure 1
Smallest individual units in a program are known as tokens. Java program is a collection of
tokens, comments and white spaces. Five types of tokens;
• Reserved keywords
• Identifiers
• Literals
• Operators
• Separators
7
1.7 Java Statements
1.8.2 Constants
Integer Constant
Sequence of digits E.g.: 123,520
Real Constant
Numbers containing E.g.:0.0083, -0.75
Single Character Constant
Contains a single character enclosed within a pair of single quotes
E.g.: ’x’, ’r’
String Constant
Sequence of characters enclosed between double quotes.
8
1.8.3 Data Types
Figure 2
Integer Types
• int
Floating Point Types
• float
• double
Character Type
• Char
Boolean Type
• Boolean
9
Table 1
1.8.4 Variables
A variable is a location in memory to hold data. Variable should be given a unique name.
General form for declaration of a variable is;
10
1.9 Type Casting
Store a value of one type into a variable of another type. There are two types of casting.
• Widening
• Narrowing
Narrowing
Assigning a larger type value to a variable of smaller type.
Widening
Automatic type conversion is possible only if the destination type has enough procession
to store the source value.
Java support rich set of operators. Operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations. Operators are used in programs to manipulate data and
variables.
Relational Operators
Comparisons can be done with the help of relational operators.
E.g.: is less than <
is less than or equal to <=
is greater than >
is greater than or equal >=
is equal to ==
is not equal to !=
11
Logical Operators
Form compound conditions by combining two or more relations.
E.g.: logical AND &&
logical OR ||
logical NOT !
Assignment Operators
Assign the value of an expression to a variable
E.g. Op=exp;
X+=y+1;
Conditional Operators
Used to construct conditional expressions of the form.
E.g. : exp1 ? Exp2: exp3
x=(a>b)? a: b;
Arithmetic Expressions
• Arithmetic expression is a combination of variables, constants and operators arranged
as per the syntax of the language.
• E.g.: a*b-c
12
Precedence of Arithmetic Operators
An arithmetic expression without any parenthesis will be evaluated from left to right using the
rules of precedence of operators. In the table below, operators with the highest precedence
appear at the top of the table, those with the lowest appear at the bottom.
Table 2
E.g.: x=a-b/3+c*2-1
step 1: x=9-4+3*2-1
step 2: x=9-4+6-1
step 3: x=5+6-1
step 4: x=5+6-1
step 5: x=10
13
1.11 Decision Making and Branching
1.11.1 Introduction
Java language processes decision making capabilities and supports following statements known
as control or decision-making statements.
– If statement
– Switch statement
– Conditional operator statement
Simple If Statement
If (test expression)
{ statement;
}
If Else Statement
If (test expression)
{true block statement;
}
else
{false block statement;
}
14
Nested If Else Statement
if (test condition)
{ if(test condition)
{ statement;
}
else
{ statement;
}
}
else
{
}
Else If Ladder
If(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
else
statement;
Switch Statement
switch ()
{
case value_1;
block-1
case value_2;
block-2
default
}
The ?: Operator
Making two-way decisions.
E.g.:
conditional expression? expression 1: expression 2
flag=(x<0) ? 0:1;
15
1.12 Decision Making and Looping
1.12.1 Introduction
While Statement
initialization
while (test condition)
{ Increment/decrement
}
Do Statement
Initialization;
do
{ Increment/decrement
}
while (test condition);
For Statement
16
Jumps In Loops
Loops perform a set of operations repeatedly until the control visible fails to satisfy the test
condition. The number of times loop is repeated is decided in advance and the test condition is
written to achieve this. When executing a loop, it is desirable to skip a part of the loop or leave
loop as soon as certain condition occurs.
An early exit from a loop can be accomplished by using the break statement. When a break
statement encountered inside a loop, the loop is immediately exited, and program continues with
the statement immediately following the loop. When the loops are nested, the break would only
exit from the loop containing it.
Example: for (int i = 0; i < 10; i++)
{ if (i == 4)
{ break;
}
System.out.println(i);
}
Skipping A Part of a Loop
It may be necessary to skip a part of the body of the loop under certain conditions.
Java support continue statement. Continue causes the loop to be continued with the next iteration
after skipping any statements in between. The continue statement tells the compiler skip the
following statements and continue with the next iteration.
Example: for (int i = 0; i < 10; i++)
{ if (i == 4)
{ continue;
}
System.out.println(i);
}
17
LESSON 02 –OBJECT ORIENTED CONCEPT
Object oriented programming is used to represent real world entity(s) in a program. The real-
world entities are books, students, trees, tables, fans…. etc. The real-world entities are called
objects in programming context.
Class is a template or blueprint which is used to create objects in programming. The class has
attributes and functions.
Attributes : age
weight
functions : walk ()
eat ()
Object represents real world entity, and an object(s) is created by a class. The student Amal and
Saman are objects which created by class Student. Values for the attributes decided by object(s).
Attributes : age = 20
weight = 6.5
Functions : walk ()
eat ()
Figure 3
18
Example : Object: Saman
Attributes : age = 18
weight = 5.8
Functions : walk ()
eat ()
• Encapsulation
• Abstraction
• Inheritances
• Polymorphism
2.3.1 Encapsulation
Wrapping Attributes and Methods together called Encapsulation. The class is the basic
unit used to implement encapsulation. Attributes are hidden by private label and those are
accessed through methods under public label.
2.3.2 Abstraction
19
2.3.3 Inheritance
2.3.4 Polymorphism
Polymorphism is used to show many forms or actions by one name. There are two types
of polymorphism. More details will be discussed.
20
LESSON 03 –CLASSES AND OBJECTS
3.1 Introduction
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism.
Class is a template which is used to create objects in programming. The class has
attributes and methods. An object is a real-world entity.
21
class Main
{ public static void main (String args[])
{ Student student_1=new Student ();
student_1. setName(“Amal”);
student_1. getName();
}
We have also seen that the variables and methods of a class are visible everywhere in the
program. It may be necessary in some situations to restrict the access to certain
variables(attributes) and methods from outside the class. For an example we may not like
the objects of a class directly alter the value of a variable or access a method.
We can achieve this in java by applying visibility modifiers to the instance variables and
methods. The visibility modifiers are also known as access modifiers.
▪ public
▪ private
▪ protected (Explained under session inheritance)
public Access
22
private Access
private fields enjoy highest level of protection. They are accessible only with their
own class. They cannot be inherited by subclasses and therefore not accessible in
subclasses. Cannot override a non-private method in a subclass and then make it
private.
this reference variable refers to the current object and it is used inside a constructor or a
method.
An object in java is essentially a block of memory that contains space to store all the
instance variables. Creating an object is also referred as instantiating an object. Objects in
java are created using the new operator.new operator creates object of the specified class
and returns reference to that object.
Each object containing its own set of variables and methods. We should assign values to
these variables in order to use them in our program.
23
3.2.5 Constructors
It would be simpler and more concise to initialize an object when it is first created. Java
support special type of method called a constructor that enables an object to initialize
itself when it is created. Features of the Constructor are;
▪ have same name as the class itself
▪ do not specify a return type
The constructor Rectangle can also be termed as parameterized constructor. Because, at the
time of object instantiation, the constructor is explicitly invoked by passing certain arguments.
class Student
{ private String name;
public Student (String name)
{ this.name=name;
}
public String getName()
{ return name;
}
}
If we want the constructor to automatically initialize the object variables with some
default values, default constructor can be used.
E.g.: default constructor
class Student
{ private String name;
public Student ()
{ this.name=”Amal”;
}
public String getName()
{ return name;
}
}
24
3.3 Static members
Static members are common for all the instances(objects) of the class, but non-static
members are separate for each instance of class.
{ basic_salary= newsalary;
Java memory management allocate and deallocate the objects. This memory management is
performed automatically using Garbage Collector. The following diagram shows run time data
areas in the memory.
Figure 4
25
Heap : Each time when object is created, memory is allocated in
the heap. This memory is free after the automatic garbage
collection.
Method Area : All class level information like class name, immediate
parent class name, methods and variables information
including static variables are stored.
JVM Stacks : Stores local variables, partial results, and data about
method calls.
Native Method Stack : This is for methods written by languages other than java.
Program Counter Registers : Stores the memory address of JVM instructions currently
executed.
26
LESSON 04 –ASSOCIATION
4.1 Introduction
Association represents relationship which is created between two classes. This shows how
objects of two classes are connected. Association represents Has-A relationships between
classes.
• Aggregation
• Composition
4.3 Aggregation
class Subject
{ String subject_name;
// Subject class constructor
Subject (String name)
{ this. subject_name = name;
}
}
class Student
{ String index;
Subject subject;
27
public static void main(String[] args) {
Subject subject=new Subject(“OOP”);
Student student = new Student ("DSEXX101", subject);
}
}
4.4 Composition
Composition is more restricted version of aggregation, and it indicates that one class includes
another class.
E.g.: class Customer has a relationship with class Account.
class Customer
{
private Account Account;
Customer (Account Account)
{ engine = en;
}
}
28
LESSON 05 –INHERITANCE
5.1Introduction
Reusability is yet another aspect of OOP. It is always nice if we would reuse something
that already exists rather than creating the same all over again. Java support this concept.
Java classes can be reused in several ways. This is basically done by creating new
classes, reusing the properties of existing ones. The mechanism of deriving a new class
from an old one is called inheritance. Old one is known as the base class | super class
|parent class and new one is called the sub class| derived class |child class.
The inheritance allows sub classes to inherit all the variables and methods of their parent
classes. Inheritance may take different forms;
▪ Single Inheritance
▪ Hierarchical Inheritance
▪ Multilevel Inheritance
29
5.2 Protected Label
The members which are declared as protected can be used or accessed by methods in the same
class, sub classes of same packages, some classes of different packages and methods in different
classes of the same package.
The keyword extends signifies that the properties of the superclass name are extended to
the subclass name.
The subclass will now contain its own variables and methods as well as those of the
superclass.
30
5.4 Subclass Constructor
A sub class constructor is used to construct the instance variables of both the sub class
and the super class. The subclass constructor uses the keyword super to invoke the
constructor method of the superclass. The keyword super is used subject to the following
conditions;
31
LESSON 06 –POLYMORPHISM
6.1 Introduction
Polymorphism means taking many forms. Here ‘poly’ means many and ‘morph’ means
forms. It is the ability of a variable, function or object to take on multiple forms.
Polymorphism allows to define one interface or method and have multiple
implementations.
▪ Method overloading
▪ Method overriding
It is possible to create methods that have the same name, but different parameter lists and
different definitions. This is called as method overloading.
32
6.2.2 Overriding Methods
The process of overriding super class method by derived class method with more specific
definition called method overriding.
All methods and variables can be overridden by default in sub classes. If we wish to
prevent the sub classes from overriding the members of the superclass, we can declare
them as final using the keyword final as a modifier.
Making a method final ensures that the functionality defined in this method will
never be altered in anyway.Similarly the value of a final variable can never be
changed.
33
6.5 Final Classes
Sometimes we may like to prevent a class being further subclasses for security reasons.A
class that cannot be subclassed is called a final subclass.This is achieved in java using the
keyword final.
6.6 Abstraction
This hides the details and showing the essential things to the user. Therefore, abstraction
helps to reduce complexity. You can achieve abstraction in two ways.
▪ Abstract class
▪ Interface
When a class contains one/more abstract methods, it should also be declared as abstract.
While using abstract classes, we must satisfy the following conditions:
We can indicate that a method must always be redefined in a subclass, thus making
overriding compulsory. This is done using the modifier keyword abstract in the method
definition.
E.g.: abstract class shape
{ abstract void draw();
}
34