0% found this document useful (0 votes)
10 views

E Book OOP

Object orient programming

Uploaded by

Mix Tube
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)
10 views

E Book OOP

Object orient programming

Uploaded by

Mix Tube
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/ 35

Contents

Lesson 01 –Language Fundamentals ............................................................................................................ 4


1.1 INTRODUCTION ............................................................................................................................. 4
1.2 JAVA ENVIRONMENT .................................................................................................................... 4
1.3 SIMPLE JAVA PROGRAM ............................................................................................................... 5
1.4 JAVA PROGRAM STRUCTURE ........................................................................................................ 6
1.5 JAVA TOKENS ................................................................................................................................ 7
1.6 JAVA STATEMENTS ........................................................................................................................ 8
1.7 CONSTANTS, VARAIBLES, ARRAYS AND DATA TYPES ............................................................ 8
1.8 TYPE CASTING ............................................................................................................................. 11
1.9 OPERATORS AND EXPRESSIONS .................................................................................................. 11
1.10 DECISION MAKING AND BRANCHING ......................................................................................... 14
1.11 DECISION MAKING AND LOOPING .......................................................................................... 16
Lesson 03 –Classes and Objects ................................................................................................................. 21
2.1 Introduction ................................................................................................................................ 21
2.2 Class and Object .......................................................................................................................... 21
2.3 Encapsulation ................................................................................. Error! Bookmark not defined.
Constructors............................................................................................................................................ 24
Lesson 05 –Inheritance ............................................................................................................................... 27
2.4 Introduction ................................................................................................................................ 29
Defining a Subclass.................................................................................................................................. 30
Subclass Constructor ............................................................................................................................... 31
Lesson 06 –Polymorphism .......................................................................................................................... 32
2.5 Introduction ................................................................................................................................ 32
There are two applications. .................................................................................................................... 32
▪ Method overloading ....................................................................................................................... 32
▪ Method overriding .......................................................................................................................... 32
Final Variables and Methods .................................................................................................................. 33
Final Classes ............................................................................................................................................ 34
Finalizer Methods ...................................................................................... Error! Bookmark not defined.
2.6 Abstraction .................................................................................................................................. 34

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.

1.2 Java Environment

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.

1.3 Simple Java Program

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 /* */

1.4 Java Program Structure

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

1.6 Java Tokens

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

A statement is an executable combination of tokens ending with a semicolon (;) mark.


E.g.: Expression statement
Labeled statement
Control statement
Synchronization statement
Guarding statement

1.8 Constants, Variables, Arrays and Data Types


1.8.1 Introduction

A programming language is designed to process certain kinds of data consisting of numbers,


characters, and strings to provide useful output known as information. These instructions are
formed using certain symbols and words according to some rigid rules known as syntax rules.

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;

type variable1, variable2


• int x;
• float y;
• double z;
• char a;
Simple method of giving value to a variable is;
• variable_name=value
• x=5;

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.

E.g.: int m=50;


byte n=(int) m;
long count=(long)m;

Widening
Automatic type conversion is possible only if the destination type has enough procession
to store the source value.

E.g.: byte b=75; int a=b;

1.10 Operators and Expressions

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;

Increment Decrement Operators


++
--
E.g.: ++m; or m++;
--m; or m—

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

1.11.2 Decision Making with If Statements

The if statement may be implemented in different forms.


o Simple if statement
o if-else statement
o Nested if else statement
o else if ladder

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

A program loop consists of two segments.


body of the loop
control statement
Looping process include;
setting and initializing of a counter
execution of the statements in the loop
Test for a specific condition
incrementing the counter
Three constructs for performing loop operations.
while
do
for

While Statement

initialization
while (test condition)
{ Increment/decrement
}
Do Statement

Initialization;
do
{ Increment/decrement
}
while (test condition);
For Statement

for (initialization; test condition; increment)

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.

Jumping Out of a Loop

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

2.1 Introduction to Object Oriented Programming

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.

2.2 Class vs Object

Class is a template or blueprint which is used to create objects in programming. The class has
attributes and functions.

Example : Class: Student

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).

Example : Object: Amal

Attributes : age = 20

weight = 6.5

Functions : walk ()

eat ()
Figure 3

18
Example : Object: Saman

Attributes : age = 18

weight = 5.8

Functions : walk ()

eat ()

2.3 Object Oriented Features

The following are main object-oriented features.

• 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

Hiding implementation details of a method is called abstraction. For an example when we


send an email, we type email address and message of the email and press compose button
to send the email. But we have no idea how compose button functionality is working as it
hides implementation from the user.

19
2.3.3 Inheritance

Inheritance provides an opportunity to re-use attributes and methods of a class(s) to


another class. There are several types of inheritance available. More details will be
discussed.

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

Java is true object-oriented language. Object-oriented programming aims to implement


real-world entities in programming. Object oriented programming has following
concepts.

• Encapsulation
• Abstraction
• Inheritance
• Polymorphism.

3.2 Class and Object

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.

Syntax : class classname


{ attributes declarations;
methods declarations;
}

Example: class Student


{ private String name;
public void setName (String name)
{ this.name=name;
}
public String getName()
{ return name;
}
}

21
class Main
{ public static void main (String args[])
{ Student student_1=new Student ();
student_1. setName(“Amal”);
student_1. getName();
}

3.2.1 Visibility Controls

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

Any variable or method is visible to the entire class in which it is defined. If we


want to make it visible to all the classes outside this class, this is possible by
simply declaring the variable or method as public.

E.g.: public void setName (String name) { this.name=name; }

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.

E.g.: private String name;

3.2.2 this keyword

this reference variable refers to the current object and it is used inside a constructor or a
method.

3.2.3 Object Creation

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.

E.g.: Student student_1=new Student ();

3.2.4 Accessing Class Members

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.

E.g.: student_1. setName(“Amal”);


student_1.name=” Amal” //This is possible if name is public.

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.

E.g.: parameterized constructor

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.

Example: class Employee

{ private static float basic_salary=50000f;

public static void changeBasicSalary(float newsalary)

{ basic_salary= newsalary;

3.4 Memory Management

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.

4.2 Types of Association

There are two types of associations available. They are

• Aggregation
• Composition

4.3 Aggregation

Aggregation indicates that class has a reference of another class.

E.g.: class Student has a relationship with class subject.

class Subject
{ String subject_name;
// Subject class constructor
Subject (String name)
{ this. subject_name = name;
}
}
class Student
{ String index;
Subject subject;

Student (String n,Subject subject)


{ this.index = n;
this.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.

Here class Account cannot exist without class Customer.

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.

Syntax: protected String name.

5.3 Defining a Subclass

Syntax : class subclassname extends superclassname


{
variables name;
methods declaration;
}

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.

Example: class Room


{ protected int length,breadth;
public int area()
{
}
}
class BedRoom extends Room
{ private int height;
public int volume()
{
}
}

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;

▪ Super may only be used within a subclass constructor method.


▪ The call to super class constructor must appear as the first statement
within the subclass constructor.
▪ Parameter in the super call must match the order and type of the instance
variable declared in the super class.
E.g.: class Room
{ protected int length,breadth;
public Room(int x,int y)
{ this.length=x;
this.breadth=y;
}
}
class BedRoom extends Room
{ private int height;
public BedRoom(int x,int y,int z)
{ super(x,y);
height=z;
}
}

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.

6.2 Types of Polymorphism

There are two applications.

▪ Method overloading
▪ Method overriding

6.2.1 Overloading Methods

It is possible to create methods that have the same name, but different parameter lists and
different definitions. This is called as method overloading.

E.g.: class Room

{ private float length, breadth;


public show (float x, float y)
{
}
public show (float x)
{
}
}

32
6.2.2 Overriding Methods

The process of overriding super class method by derived class method with more specific
definition called method overriding.

E.g.: class super


{ void display()
{
}
}
class sub extends super
{ void display()
{
}

6.3 Final Variables and Methods

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.

E.g.: final int size=100;

final void showstatus();

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.

E.g.: final class Aclass{}


final class Bclass extends someclass{}
Any attempt to inherit these classes will cause an error and the compiler will not allow it.

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 cannot use abstract classes to instantiate objects directly;


▪ the abstract methods of an abstract class must be defined in its sub class.
▪ we cannot declare abstract constructors or abstract static methods.

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

You might also like