0% found this document useful (0 votes)
4 views60 pages

Java Programming Module

The document provides a comprehensive overview of Object-Oriented Programming (OOP) principles, comparing it with procedural programming and highlighting key concepts such as encapsulation, abstraction, inheritance, and polymorphism. It also introduces Java programming elements, including the Java development environment, basic syntax, variable declaration, and the distinction between classes and objects. The content aims to familiarize students with OOP and Java programming fundamentals, emphasizing program reusability and extensibility.
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)
4 views60 pages

Java Programming Module

The document provides a comprehensive overview of Object-Oriented Programming (OOP) principles, comparing it with procedural programming and highlighting key concepts such as encapsulation, abstraction, inheritance, and polymorphism. It also introduces Java programming elements, including the Java development environment, basic syntax, variable declaration, and the distinction between classes and objects. The content aims to familiarize students with OOP and Java programming fundamentals, emphasizing program reusability and extensibility.
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

Debere Tabor University

Gafat Technology Institute

Department of Electrical and computer


Engineering

Course Module for Object Oriented Programming


Chapter One
Object-Oriented Programming (OOP)

Objectives: the main objective of this programming is to familiarize you to OOP and
understand how it can be more important than procedural programming. Besides it is expected
of you to:
 Understand and explain OOP principles
 Describe program reusability and extensibility

1.1 Comparison between Procedural and Object-Oriented Programming


Programming is a creative process carried out by programmers to instruct a computer on how
to do a task. A program is a set of instructions that tells a computer what to do in order to come
up with a solution to a particular problem. There are a number of alternative approaches to the
programming process in finding such solutions referred to as programming paradigms. Next
we will be seeing and differentiating the two of them.

I- Procedural Programming

Procedural programming uses a list of instructions to tell the computer what to do step-by-step.
Procedural programming relies on - you guessed it - procedures, also known as routines or
subroutines. A procedure contains a series of computational steps to be carried out.

Procedural programming is intuitive in the sense that it is very similar to how you would expect
a program to work. If you want a computer to do something, you should provide step-by-step
instructions on how to do it.

Examples of procedural languages: Fortran, COBOL and C.

II- Object-Oriented Programming

OBJECT-ORIENTED PROGRAMMING (OOP) represents an attempt to make programs


more closely resemble the way people think about and deal with the world. In the older styles
of programming, a programmer who is faced with some problem must identify a computing
task that needs to be performed in order to solve the problem. Programming then consists of
finding a sequence of instructions that will accomplish that task. But at the heart of object-
oriented programming, instead of tasks we find objects – entities that have behaviors, that hold
information, and that can interact with one another.

Key Differences

One of the most important characteristics of procedural programming is that it relies on


procedures that operate on data - these are two separate concepts. In object-oriented
programming, these two concepts are bundled into objects. This makes it possible to create
more complicated behavior with less code. The use of objects also makes it possible to reuse
code. Once you have created an object with more complex behavior, you can use it anywhere
in your code.

The need for OOP paradigm:

OOP enable a programmer to build reliable, user friendly, maintainable, well documented,
reusable software systems that well fulfills the requirements of its users.

A problem of building a car can be treated in both the structured as well an OOP
paradigm. Come out how it could be treated in both cases.

1.2 Basic principles of Object-Oriented Programming


1.2.1 Data Encapsulation

Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps
both safe from outside interference and misuse. It is a principle of hiding information and data
from an outside access.
Example:
We can use a Google interface to browse round the internet but we cannot directly access and
change the mechanisms and the data used within a Google Database.
Structured Programming Object Oriented Programming
Fig 1: A diagrammatical representation of encapsulation in SP and OOP

Data defined within an object can be made to be private or public for an external access. In
the later case other objects can access the data and they cannot stay hidden. Thus,
polymorphism is not supported in a public modifier.
Data encapsulation is basically used to obtain information hiding or data hiding.

1.2.2 Data Abstraction

Data Abstraction is the mechanism of retrieving essential details by hiding the background
details. It is a way of modeling the real-world objects by taking the relevant information and
removing unnecessary details that add complexity for the model.
Example: A motor cycle can be defined to be a movable non-living object with two wheels that
drives using a motor.

Would it be feasible to define a car as a movable non-living object that has at least four
wheels, a motor, a chassis system, a speedometer that tells speed information,
electronic system that use a car battery, one or more chairs in which people can sit on,
a brake that can be of different forms, thousands of different components, a chain that
transmits power from one toothed wheel to another in a mechanical system…which
were invented by… ( uufffffah!)

How do you rather define a car in an abstract way


What are actually abstract paintings?
1.2.3 Inheritance

Inheritance is a form of software reuse in which a new class is created by absorbing an existing
class’s members and adding them with new or modified capabilities. It highly resembles the
natural way of inheriting resources from our parents.
The class which is giving data members and methods is known as Base class or super class/
parent class. The class which is taking data members and methods from the base class is known
as sub class or derived class/child class.
Advantages of inheritance
 Code redundancy is significantly reduced especially in large programs. Hence, we can
get consistence of the program and less memory.
 Save time during program development by reusing proven high-quality software
 On overall the performance of the application is well improved.
1.2.4 Polymorphism

Polymorphism (from the Greek, meaning ―many forms‖) is a feature for an object to exist in
different (many) forms.

Example: A real object student can be treated as both a student and a human being. As a student
it might have grade level, section, department, CGPA, etc… and associated behaviors like
studying, attending class. At the same time a student is a human being and can have different
personal, social, political etc… status and behavior that human beings have and/or perform.

Summing up the example: A student can act as both a student and as a human being.

Polymorphism is mainly used to build dynamic programs.

1.3 Program reusability and extensibility


When you declare a class, you may reuse its declaration in different dimensions: One such
reuse is the trivial case of using a class declaration in creating multiple instances. The following
to code reuse principles use other class declarations within their declarations or
implementations.
I- Composition
When you declare an instance of a class within another object, this reuse is called composition
or association depending on the relation between the creating object and created object. The
ordinary association between two classes describes a relationship that will exist between
instances at run-time. That is, one object is used by another object in the program by means of
reference variables.
On the other hand, compositions are special associations that represent whole part
relationships. If there is a composition relationship between two classes, the instances of the
parts is really a part of instances of the aggregate.
II- Inheritance
The second kind of reuse is the reuse of class structure through inheritance. Inheritance is one
of the key elements of object-oriented programming languages. If different classes have similar
states and provides similar service, inheritance allows us to reuse those similar parts from a
generalized class declaration. This is accomplished through creating an abstract base class and
reusing its state and behavior in more specialized classes.

Self-review exercise
1. List out the basic difference between procedural programing and object-oriented
programing?
2. Describe what’s encapsulation, abstraction and information hiding?
3. Define and describe the difference between inheritance and polymorphism?
Chapter 2
Introduction to Java Elements
Objectives: the main objective of this chapter is to enable you understand the basic Java
Program Structure elements and start simple Java programs. In addition:

 Describe about the Java development environment


 Construct basic programs using variables and their declaration
 Explain classes and objects
 Develop input/output constructs
 Create programs that involve conditional statements and loops
 Demonstrate Arrays

2.1 Introduction to the Java Development Environment


Compiled and Interpreted languages:
 In compiled languages: the program codes (high level instructions) are compiled
directly to machine language.

Example: C, C++

Fig: showing the role of a compiler in Compiled languages

Different Operating Systems (Mac, Unix, Windows) require different machine codes
and thus different compilers.
In Interpreted languages: the compiler does not produce machine code directly rather a
machine-like code Known as bytecode. Then the byte code is interpreted by different
machines (platforms) to a corresponding machine language that can be executed and
installed.
Fig 1: a diagram showing how interpreted languages perform
The Java Virtual Machine is responsible for the interpretation of the Byte Code into a machine
code for execution in a particular Operating System.

JVM shall be installed on the particular OS for translating the bytecode into appropriate
machine code.
Can a single JVM be used for different platforms (OS)?
List the 11 Java Buzzwords. What is meant by each of the words?

Java Advantages

Java is platform independent, safe, robust, high performance, multithreaded and secured.

Explain how the above mentioned characters make Java advantageous.

Java Disadvantages

• Running byte code through the interpreter is not as fast as running machine code, which
is specific to that platform.

• Because it is platform independent, it is difficult to use platform specific features (e.g.,


Windows Taskbar, Quick Launch) in Java.

• Java interpreter must be installed on the computer in order to run Java programs.
Choosing a User Interface Style

Two choices:

• Graphical user interface (GUI): Program interacts with users via “windows”
with graphical components

• Terminal I/O user interface: Programs interact with users via a command
terminal

• MS-DOS console or Unix terminal

2.1.1 Java Basics

When we consider a Java program, it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what do class, object, methods
and instance variables mean.
Object - Objects are real world instances that have states and behaviors. Example: A dog has
states-color, name, and breed as well as behaviors -wagging, barking, and eating. An object is
an instance of a class.
Class - A class can be defined as a template/blue print that describes the behaviors/states that
object of its type support. It is like a ‘building plan’ which is used to construct ‘houses’.
Methods - A method, also called function or procedure in other languages, is basically a set of
procedures which produces a certain output. A method defines the behavior that an object can
have. A class can contain many methods. It is in methods where the logics are written, data is
manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.

Java Identifiers:
All Java components require names. Names used for classes, variables, constants, methods and
packages are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:

 Identifiers can contain letters, numbers, currency character, or underscore characters


but not any other characters are allowed
 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or
an underscore (_).
 After the first character, identifiers can have any combination of characters.
 A keyword cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
 An identifier cannot be true, false, or null.
o An identifier can be of any length

Java Keywords:
Keywords are words that have unique meaning in Java and cannot be used as constant or
variable
or as identifier names. The following list shows the reserved words in Java.

Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There
are two categories of modifiers:
 Access Modifiers: default, public, protected, private
 Non-access Modifiers: final, abstract, strictfp, static etc…
Come out with what each of the access modifiers are.

Comments in Java:

Comments are phrases, sentence or a short paragraph that give clarifications about certain code
elements in a Java program. Comments are ignored by the compiler and not executed as
program files. Java supports the following three commenting styles:
 Single line Comment ( // ): all statements in same line after // are ignored
 Block Comment (/* */): all statements within /* and */ are ignored
 Documentation Comment (/** */): it is like the block comment but has an extra
advantage of generating documentations for certain code elements in a program.
2.1.2 Basic Syntax Conventions in Java:

About Java programs, it is very important to keep in mind the following points.
Case Sensitivity - Java is case sensitive.
Class Names - For all class names, the first letter should be in Upper Case. If several words
are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter. If several words are
used to form the name of the method, then each inner word's first letter should be in Upper
Case.
Example: public void myMethodName()
Program File Name - Name of the program file should exactly match the class name.

2.2 Variables and their Declaration


2.2.1 Variables
Variables are used to store values to be used later in a program. They are called variables
because their values can be changed. Variables are for representing data of a certain type that
can be int, double, float, char … or any of the ADTs.

There are three kinds of variables:


 Local Variables
 Class Variables (Static Variables)
 Instance Variables (Non-static variables)
 A variable should be declared first before it is used.

2.2.2 Variable Declaration


Variable declaration tells the compiler to allocate appropriate memory space for the variable
based on its data type.

 The syntax for declaring a variable is

datatype variableName;
Examples of variable declarations:

 int count; // Declare count to be an integer variable;

 double radius; // Declare radius to be a double variable;

 double interestRate; // Declare interestRate to be a double variable;

 If variables are of the same type, they can be declared together, as follows:

datatype variable1, variable2, ..., variablen;

Example; int i,j,k;

double radius,area;

By convention, variable names are in lowercase. If a name consists of several words,


concatenate all of them and capitalize the first letter of each word except the first.

Examples of variable names:


radius, speed, interestRate
2.2.3 Initializing variables
Variables shall hold some value. ‘ = ‘ sign is used to assign a value to a variable once it is
declared.

Example: int i;
i = 10;
 Variables can be declared and initialized in one step.

Example: int count = 1;


2.2.4 Assignment Statements and Expressions
After a variable is declared, you can assign a value to it any time you want by using an
assignment statement. In Java, the equal sign (=) is used as the assignment operator.

• The syntax for assignment statements is as follows:

variable = expression;

Expression: is any computation involving values, variables, and operators that evaluates to a
value.

Examples: int x = 1;
x = 5 * (3 / 2) + 3 * 2;
x = 5*(x-y+2);
1, x, 2*x+3, 5*(x-y+2) … are all examples of expressions when x and y are valid
variables.

A variable can also be used in an expression. For example,

x = x + 1;
2.2.5 Named Constants
Named constant: or simply constant represents permanent data that never changes throughout
the program. Constants are used when a certain constant value is used repeatedly within the
same program.

The syntax for declaring a constant:

final datatype CONSTANTNAME = VALUE;

Example: final double PI = 3.1417;


By convention, constants are named in uppercase: PI, not pi or Pi.

2.3 Introduction to Objects and Classes


Introduction: Review of Procedural vs. Object Oriented Programming

Fundamentally programming any system has two aspects

⚫ Data

⚫ Code that changes the data

These two aspects are handled quite differently in Procedural Systems & OO Systems. In PP
code is placed into small procedures that use and change it. Such procedures are written as
functions in C/C++. The functions take some input, do something then produce some outputs.
Key idea: the functions have no intrinsic relationship with the data they operate on. Instead to
get the desired output the correct number and type of arguments are passed to the
functions/procedures. But there are times we need to access data not provided as a parameter:
“global” or “shared” data. In such a PP case global data is separate from the functions: this is
the problem.

 It is easy to modify data outside your scope


 Access to data is uncontrolled and unpredictable
 Testing and debugging are much more difficult
 If you need to change the shared variable, adjustments
have to be made each place it appears in your code.
 This is difficult to manage in large systems.

How is this handled in Objectville?

In OOP data and related functions are put together into an “Object”. The data inside an object
can be manipulated by calling the object’s functions. The data is locked away inside the objects
and can only be accessed using the functions within the object. Objects can never operate on
shared or global data and thus ensuring data controversies and unpredictability rising in PP
paradigm alleviated in OOP.

2.3.1 What exactly is an Object?


Objects are instances of the real world which can be uniquely identified.
- A student, a car, a chair, a square, an apple, an SMS, etc … are good examples of an
object.

Objects can be real or abstract.


An object is defined and differentiated by both of the following two terms
- Attributes (State) and
- Behaviors
The state represents the set of properties (data fields) with the corresponding current values
that an object has.
Behavior represents the set of operations (methods) that are permissible on the object or actions
that the object can do.

A generic Object overviews

Fig: a generic figurative model for an object


Example 1: A dog object
Object states: color, height, weight, name, etc
Object behaviors: barking, breathing, biting, eating etc…
Example 2: A bank account
Object States: amount, interest, debit
Object behaviors: withdraw, transfer, deposit etc…
2.3.2 Classes
 A class is a grouping of similar objects.
 It describes a collection of related objects.
 Classes can be thought of as the template/ blueprint from which objects are created.

It is like the building plans used to construct house objects.


Class Example 1: a group of dogs makes a Dog class

Class Example 2: a group of circles make a Circle class

In software a class is like a ‘building plan’ used to build houses of different types.
It defines the attributes and the methods that an object shall have.
2.4 Input/output
Input outputs in Java normally can take two forms. Input/output to RAM i.e. way of interacting
with a running program or input/output to Hard Disk like in the case for file management
systems. Now we will be seeing the first.

2.4.1 Output

To print output to the “standard output stream” ( i.e. console window) we call
[Link].

Example:

public class FirstSample


{
public static void main(String[] args)
{
[Link](“Hmmm! DTU 3rd year ECE…”);
}
}
2.4.2 Reading Input: Scanner
Reading input from the “standard input stream” [Link] is not straightforward. To read
console input, you first need to construct a Scanner that is attached to [Link]:

Scanner input = new Scanner([Link]);


Now you can use various methods of the Scanner class to read input.

Example

String fullname = [Link](); // accepts strings


String fullname = [Link](); // accepts an int value

2.5 Execution Flow Control in Java


2.5.1 Using Selection Statements:
A selection statement allows the conditional execution of a block of statements. If a condition
is true, a block of statements will be executed once, else it will be skipped.

Two types:
 The if Statements
 The switch Statement

[Link] The if statements

• The if Construct
• The if- else Construct
• The if- else if Construct
• The if- else if -else Construct
• Summary of the if Constructs

The if construct:

The if construct allows the execution of a single statement or a block of statements

Construct:
if (expression) {
// if expression returns true, the statement(s) in this block are
executed
}

The <expression> statement takes a boolean value.

The if-else construct

If a condition is true, the first block of code will be executed, otherwise the second block of
code will be executed.

Construct:
if (expression) {
// if expression returns true, statement(s) in this block is (are)
executed
}
else{
// if expression returns false, statement(s) in this block is (are)
executed
}

The if- else if construct

You can handle multiple blocks of code, and only one of those blocks will be executed at
most.
Construct:
if (expression1) {
// if expression1 returns true, statement(s) in this block is (are) executed
}
else if (expression2){
// if expression1 returns false and expression2 returns true, statement(s)
in
this block is (are) executed
}
else if (expression3){
// if both expression1 and expression2 returns false and expression3
returns
true, statement(s) in this block is (are) executed
}

The if-else if- else construct


Enables you to handle multiple blocks of code and ensure that one of them will certainly be
executed.

Construct:

if (expression1) {
// if expression1 returns true, statement(s) in this block is (are) executed
}
else if (expression2){
// if expression1 returns false and expression2 returns true, statement(s)
in
This block are executed.
}
else if (expression3){
// if both expression1 and expression2 returns false and expression3
returns
true, statement(s) in this block is (are) executed
}
else{
// if expression1, expression2, expression3 returns false, statement(s) in
this
block is (are) executed
}

Summary of if-constructs

 a single expression: if where it is possible that no block will be executed, and if-else
where one block will certainly be executed.
 multiple expressions: if-else if where it is possible that no block will be executed, and
if- else if- else where one block will certainly be executed.

[Link] The switch statement


Used to make the choices for multiple blocks with the possibility of executing more than one
of them.
Construct:

switch( case)
{
case case1:
//statements
case case2:
//statements

case caseN:
//statements
default:
//statements
}

Rules:
• if case evaluates to any of the case values i.e. case1, case2, … case N, all statements
under the starting from the statements where the case argument has returned to are
executed.
• If the case does not return to any of the values mentioned, statements under the default
construct are executed.
• It is not a must to have a default construct.

Notes:

 The argument of switch() must be one of the following types: byte, short, char, int, or

enum.
 The argument of case must be a literal integral type number or a char
 There should be no duplicate case labels

The default block:

The default does not have to be at the end of the switch. When the execution control faces a
default block, it executes it if there is no break statement in the default block, there will be fall
through just like in any other block.

The break statement:


The break statement tells the computer to exit the switch statement. When the break statement
is executed no more statement below it are executed.
For example:

switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
default:
default_statement;
break;
}

2.5.2 The loop (Iteration) statements


The loop (iteration statements) constructs are constructs used to execute a block of statements
over and over again as long as a certain condition is true.

There are four iteration constructs in Java:

 While
 do-while
 for
 for-each

[Link] The while loop


A block is executed for the first time only when a condition is true. After execution, the
condition is checked again, and as long as the condition stays true, the block is executed
repeatedly.

The code block in the while loop may not be executed at all

while ( < expression>) {


//if the <expression> is true, execute the statements in this block.
// after the execution, go back and check the condition again.
}
[Link] The do-while loop construct
A block is executed first and then checked for the condition. If the condition is true, then the
loop is repeated till the condition is false.

The do-while loop will be executed at least once.


[Link] The for loop construct:

 <statement>: initialize the iteration variable, executed only once.


 <test>: A 22oolean condition. The for block is executed repeatedly until the <test>
returns false.
 <expression>: Executed immediately after the execution of the for block.

Block breaker statements


to quit either the current iteration of a loop or the entire loop altogether:
 The continue Statement
 The break Statement

The continue statement


When this statement is executed, the current iteration is terminated, and the control jumps to
the next iteration:
 while, do-while: jumps to the Boolean condition
 for: jumps to the <expression> in the for (<statement>; <test>; <expression>)
statement.
Example:
Continue in nested loops:
In nested loops it is needed to specify from which loop you need to continue the next iteration:
the labeled continue statement.
Example:
The following program wants the execution control to jump from an inner block to an outer
block:
The beginning of the outer block will be labeled

The break statement:

The break statement throws the execution control out of the block altogether
 used either in a loop or in a switch block
 In case of nested loops, you might need to tell from which loop you want to break: the
labeled break statement.

Example:
2.6 Arrays
An array is a data structure that stores a collection of values of the same type each value being
stored in a particular compartment. Each compartment is appropriately sized for the particular
data type the array is declared to store.
An array can hold only one type of data!

Example: int[] can hold only integers


char[] can hold only characters

2.6.1 Declaring an Array Variable

Array declarations use square brackets.

datatype[] label;

Example: int[] prices;


String[] names;

2.6.2 Creating a New "Empty" Array:


An array is created by using the keyword new. The following example shows how to create a
new array with 20 compartments i.e. that holds 20 different values.

Example: int[] prices = new int[20];

The new keyword creates an array of type int that has 20 compartments
The new array can then be assigned to the array variable prices:
When first created as above, the items in the array are initialized to the zero value of the data
type

int: 0
double: 0.0
String: null
2.6.3 Constructing Arrays

To construct and use an array, you can declare a new empty array and then assign values to
each of the compartments.

String[] names = new String[5];


names[0] = “Aisha”
names[1] = "Abebe beso yemibelaw";
names[2] = "Leilt";
names[3] = "Jamal";
names[4] = "Ashenafi";

Another Way to Construct Arrays:

All of the items in an array can be specified at the array’s creation. Use curly brackets to
surround the array’s data and separate the values with commas:

Example 1:

String[] names = { "David", "Qian", "Emina", "Jamal", "Ashenafi"};


 Note that all the items must be of the same type. Here they are of type String.
Example 2:

int[] powers = {0, 1, 10, 100};


Length of an array:

The length method is used to return the size, # of compartments.

Example:

String[] names = {"David", "Qian", "Emina", "Jamal", "Ashenafi" };


int numberOfNames = [Link];
[Link](numberOfNames);

Output: 5

Important: Arrays are always of the same size: their lengths cannot be changed once they are
Created!

Example:

String[] names = {"Aisha", "Tamara", "Gikandi", "Ato", "Lauri"};

for(int i = 0; i < [Link]; i++){


[Link]("Hello " + names[i] + ".");
}
Output:
Hello Aisha.
Hello Tamara.
Hello Gikandi.
Hello Ato.
Hello Lauri.

Modifying Array Elements:

Example:

names[0] = “Bekele"
Now the first name in names[] has been changed from "Aisha" to "Bekele". So the
expression names[0] now evaluates to "Bekele".
Note: The values of compartments can change, but no new compartments may be added.

Example:

int[] fibs = new int[10];


fibs[0] = 1;
fibs[1] = 1;
for(int i = 2; i < [Link]; i++) {
fibs[i] = fibs[i-2] + fibs[i-1];
}
After running this code, the array fibs[]contains the first ten Fibonacci numbers:
1 1 2 3 5 8 13 21 34 55
2.6.4 2-Dimensional Arrays:

The arrays used so far can be thought of as a single row of values. A 2-dimensional array can
be thought of as a grid (or matrix) of values with each element of the 2-D array is accessed by
providing two indexes: a row index and a column index.

We declare a 2D array with two sets of square brackets:

dataType [][] variableName = new dataType[n][m];

where n is the number of rows and m is the number of columns.

Example:
double[][] heights = new double[5][10];
To access the acre at row index i and column index j the following syntax is used where
0 ≤ i≤ n-1 and 0 ≤ j≤ m-1 .
heights[i][j];

Example: to access row index 11 and column index 23 the syntax is:
heights[11][23];

Self-review exercise
1. Write four different Java statements that each add 1 to integer variable x.
2. Write Java statements to accomplish each of the following tasks:
a) Assign the sum of x and y to z, and increment x by 1 after the calculation. Use only
one statement.
b) Test whether variable count is greater than 10. If it is, print "Count is greater than
10".
c) Decrement the variable x by 1, then subtract it from the variable total. Use only one
statement.
d) Calculate the remainder after q is divided by divisor, and assign the result to q.
Write this statement in two different ways.
3. Write a Java statement to accomplish each of the following tasks:
a) Declare variables sum and x to be of type int.
b) Assign 1 to variable x.
c) Assign 0 to variable sum.
d) Add variable x to variable sum, and assign the result to variable sum.
e) Print "The sum is: ", followed by the value of variable sum.
4. Combine the statements that you wrote in Exercise 4.5 into a Java application that
calculates and prints the sum of the integers from 1 to 10. Use a while statement to
loop through the
calculation and increment statements. The loop should terminate when the value of x
becomes 11.
5. Determine the value of the variables in the following statement after the calculation is
performed. Assume that when the statement begins executing, all variables are type
int and have the
value 5.
product *= x++;
6. Identify and correct the errors in each of the following sets of code:
a) while ( c <= 5 )
{
product *= c;
++c;
b) if ( gender == 1 )
[Link]( "Woman" );
else;
[Link]( "Man" );
7. What is wrong with the following while statement?
while ( z >= 0)
sum += z;
Chapter Three
Classes and Objects: A deeper look

Objectives: the main objective of this chapter is to enable you abstract the real world problems
in software using objects and classes. Besides to the aforementioned main target the following
specific tasks are expected after completing the chapter.

 Understand and Model classes, objects


 Understand and develop Methods
 Work with Constructors
 Demonstrate composition
 Explain about the Static and final key words
 Creating programs using Constructors and destructors
 Explain how to use the UML class and Composition diagrams

3.1 Objects and Classes:

3.1.1 Objects

Object-oriented programming (OOP) involves programming using objects. An object


represents
an entity in the real world that can be distinctly identified. For example, a student, a desk, a
circle, a button, and even a loan can all be viewed as objects. An object has a unique identity,
state, and behavior.

 The state of an object (also known as its properties or attributes) is a set of data fields
with their current values.

Examples:

 A circle object can be defined to have a data field radius, which is the property that
characterizes a circle.
 A rectangle object has data fields width and height, which are the properties that
characterize a rectangle.
■ The behavior of an object (also known as its actions) is defined by methods. To invoke a
method on an object is to ask the object to perform an action.

Example:

 A method named getArea() can be defined for circle objects. A circle object may
invoke getArea() to return its area.

3.1.2 Classes

Objects of the same type are defined using a common class. A class is a template, blueprint, or
contract that defines what an object’s data fields and methods will be. An object is an instance
of a class. You can create many instances of a class. Creating an instance is referred to as
instantiation. The terms object and instance are often interchangeable.

The following fig shows a definition for a class named Circle:

From the above declaration of a class as many objects as desired can be created (instantiated).
An object instantiation uses a keyword new.
Example: Circle c1 = new Circle();
Circle c2 = new Circle();
Circle c3 = new Circle();
The syntax for creating a class is:

accessModifier class ClassName{


//list of variables

// list of Methods

}
Example:

public class Circle{

double radius; A data field holding the value of


radius

public double getArea(){


return radius*radius*[Link]; A method that returns an area
}

public double getPerimeter(){


return 2*[Link]*radius; A method that returns perimeter
}
}

Running Circle class defined above:


In order to run the above Circle class, another class with a main method must be constructed
which instantiates objects of type Circle.

Example:
public class TestCircle1 {

public static void main(String[] args) {

Circle c1 = new Circle();


Circle c2 = new Circle(1.0);
Circle c3 = new Circle(2.7);

[Link]("The area of the circle of radius " + [Link] + " is "


+ [Link]() );

[Link]("The area of the circle of radius " + [Link] + " is "


+ [Link]() );

[Link]("The area of the circle of radius "+ [Link] + " is "


+ [Link]() );
}
}
3.1.3 Declaring and Creating Objects

A class is essentially a programmer-defined type. A class is a reference type, which means that
a variable of the class type can reference an instance of the class. The following statement
declares the variable myCircle to be of the Circle type:

Circle myCircle;

The variable myCircle can reference a Circle object. The next statement creates an object
and assigns its reference to myCircle:

myCircle = new Circle();

Using the syntax shown below, you can write a single statement that combines the declaration
of an object reference variable, the creation of an object, and the assignment of an object
reference to the variable.

ClassName objectRefVar = new ClassName();


Note: Arrays are treated as objects in Java. Arrays are created using the new operator.
An array variable is actually a variable that contains a reference to an array.
3.1.4 Accessing an Object’s Data and Methods

After an object is created, its data can be accessed and its methods invoked using the dot
operator
(.), also known as the object member access operator:

 [Link] references a data field in the object.


 [Link] (arguments) invokes a method on the object.

For example, [Link] references the radius in myCircle, and [Link]()


invokes the getArea method on myCircle. Methods are invoked as operations on objects.

Note: Note that static variables and methods are accessed using Class while instance
variables are accessed using Objects.
Example:
public class AccessingFieldsExample{
static int value1;
int value2;
}
In this simplified example if we have an instance object object1 i.e.
AccessingFieldsExample object1 = new AccessingFieldsExample();
Then the following accessing ways for the variables defined within the class definition are
right:
AccessingFieldsExample.value1;
object1.value2;
But it is a mistake to use the following ways:
AccessingFieldsExample.value2;
object1.value1;
3.1.4 Differences between Variables of Primitive Types and Reference Types

Every variable represents a memory location that holds a value. When you declare a variable,
you are telling the compiler what type of value the variable can hold. For a variable of a
primitive type, the value is of the primitive type. For a variable of a reference type, the value
is a reference to where an object is located.

3.1.5 Using Standard Java Classes

1. The Random Class

One way to generate random numbers is to use the [Link] class, which can generate
a random int, long, double, float, and boolean value.
Example: Random k;
k = new Random();

int l;
l = [Link]( ); generates an int value from all the int set.
l = [Link](3); generates a non-negative integer number less than 3.

How are double and Boolean values generated.

2. The DATE Class

The date class contains important methods to use for various applications. Please see why and
how such methods are used.

3. The String Class

A string is a sequence of characters. In many languages, strings are treated as an array of


characters, but in Java a string is an object. The String class has 11 constructors and more than
40 methods for manipulating strings. Not only is it very useful in programming, but also it is a
good example for learning classes and objects.
Constructing a String:

A string object can be created from a string literal or from an array of characters. To create a
string from a string literal, use a syntax like this one:

String newString = new String(stringLiteral);

The argument stringLiteral is a sequence of characters enclosed inside double quotes. The
following statement creates a String object message for the string literal "Welcome to Java".
String message = new String("Welcome to Java");

Java treats a string literal as a String object. So, the following statement is valid:

String message = "Welcome to Java";

You can also create a string from an array of characters. For example, the following statements
create the string “Good Day”:

char[] charArray = {'G', 'o', 'o', 'd', ' ', 'D', 'a', 'y'};
String message = new String(charArray);
Operations within Strings:

I- String Comparisons

How do you compare the contents of two strings? You might attempt to use the = = operator,
as follows:

if (string1 = = string2)
[Link]("string1 and string2 are the same object");
else
[Link]("string1 and string2 are different objects");

Does the above code returns the equality of string contents? What does the ==
operator really perform in String comparisons?

To check equality of contents the equals method shall be used. The code given below, for
instance, can be used to compare two strings:

if ([Link](string2))
[Link]("string1 and string2 have the same contents");
else
[Link]("string1 and string2 are not equal");
For example, the following statements display true and then false.

String s1 = new String("Welcome to Java");


String s2 = "Welcome to Java";
String s3 = "Welcome to C++";
[Link]([Link](s2)); // true
[Link]([Link](s3)); // false
The compareTo method can also be used to compare two strings. For example, consider the
following code:
[Link](s2)

The method returns the value 0 if s1 is equal to s2, a value less than 0 if s1 is lexicographically
(i.e., in terms of Unicode ordering) less than s2, and a value greater than 0 if s1 is
lexicographically greater than s2.

II- Getting String Length, Extracting Characters, and Combining Strings

The String class provides the methods for obtaining length, retrieving individual characters,
and concatenating strings; length(), charAt(i: int) and concat(s: String) respectively.

Example: String s = new String(“Hello!”);


[Link](); // returns 6
[Link](2); // returns l
[Link]( “World…”); // returns Hello! World…
In addition to concat method in a String class ‘+’ can be used to perform string concatenation.
So the statement:
String s3 = [Link](s2); statement is equivalent to String s3 = s1 + s2;

III- Obtaining Substrings

A substring can be extracted from a string using the following two substring method in the
String class.

substring(beginIndex: int): String

substring(beginIndex: int, endIndex: int): String

Example:

String message = "Welcome to Java";

[Link](11); returns Java

[Link](0,8); returns Welcome

 See the remainder methods in a String class to have a better understanding


and manipulation of Strings.
3.1.6 Array of Objects

In addition to arrays of primitive types arrays of Object types can be created. For example, the
following statement declares and creates an array of ten Circle objects:

Circle[] circleArray = new Circle[10];

How are arrays of object type initialized? Is there any difference from the way arrays
of primitive data types are initialized?

3.2 Methods
A method (called functions or procedures in other languages) is a collection of statements
grouped together to perform an operation. Methods allow you to modularize a program by
separating its tasks into self-contained units thus providing ease to program management and
software reusability.

3.2.1 Declaring Methods:


Methods capture a piece of computation we wish to perform repeatedly into a single
abstraction.
Methods in Java have 4 parts:
 return type,
 name,
 arguments,
 body.

The syntax for defining a method is as follows:

returnType name (list of parameters (arguments))


{
// body;
}

Example: double sqrt(double num)


{
// a set of operations that compute the square root of a number
}
The type, name and arguments together is referred to as the signature of the method

Example: double sqrt(double num); is the signature of sqrt method.


Return Statements
The return statement makes a method to exit immediately after it execution. The return
statement is usually the last statement in a method.

Can a method have multiple return statements?

3.2.2 Invoking Methods

To call a method, the name of the method followed shall be specified with a list of comma
separated arguments in parentheses:

Example: sqrt(4); // Computes 210 with

If the method has no arguments, the method name shall be written followed with empty
parentheses:

Example: size(); // a method named size with no parameters

3.2.3 Static Methods


Some methods have the keyword static before the return type:

static double divide(double a, double b)


{
return a / b;
}

Static methods like static variables that directly belong to a class. They are can be called by
specifying the name of the class followed by a dot operator and the name of the method.
Example: the static method, power method, within the Math class can be called as follows:
[Link](2,10); // Computes 210
NB: objects can never act on (access) the static methods and variables.
3.2.4 The main method
The main method is where a Java program always starts when you run a class file with the java
command
The main method is static and has a strict signature which must be followed:

public static void main(String[] args) {


...
}
3.2.5 Recursive methods
Recursive methods are methods which call themselves within their method definitions.
Example:

class Factorial {

public static int fact(int n)


{
if (n <= 1)
return 1;
else
return n * fact(n – 1);
}
}

3.2.6 Overloading Methods

The Java programming language supports overloading methods, and Java can distinguish
between methods with different method signatures. This means that methods within a class can
have the same name if they have different parameter lists.

• In the Java programming language, you can use the same name for all the drawing methods
but pass a different argument list to each method. Thus, the data drawing class might declare
four methods named draw, each of which has a different parameter list.

• Overloaded methods are differentiated by the number and the type of the arguments passed
into the method.

• You cannot declare more than one method with the same name and the same number and
type of arguments, because the compiler cannot tell them apart.

• The compiler does not consider return type when differentiating methods, so you cannot
declare two methods with the same signature even if they have a different return type.

Example:

public void method1(int a)


{
// body1
}

public void method1(double a)


{
// body2
}

The above two methods are compiled as different methods and if we pass an int argument in to
method1, the first method will be called and body1 is executed. If, in other ways, an argument
of type double is passed to method1, the second method will be called and body2 is executed.

i.e. method1(4); // invokes the first method (body1 executed)


method1(4.5); // invokes the second method (body2 executed)

NB: It is a mistake to try to overload methods just by varying the return type.
Example:

public int method1(int a)


{
// body1
}
public double method1(int a)
{
// body1
}

3.3 Constructors

Constructors are a special kind of method within a class definition. Constructors are mainly
used to initialize data fields but can also be used to perform different actions. Constructors are
invoked when creating new Objects. Every class shall have a constructor defined. Even if we
don’t create our own, Java creates one for us initializing all the data fields to their default value
e.g. an int to ‘0’ and a String to “null”.

A constructor has the following three peculiarities.


 A constructor must have the same name as the class itself.
 Constructors do not have a return type—not even void.
 Constructors are invoked using the new operator when an object is created.
Constructors play the role of initializing objects.

Example:

class Circle {
double radius = 1.0;

Circle() {
}
Constructors
Circle(double newRadius) {
radius = newRadius;
}

double getArea() {
return radius * radius * [Link];
}
}
3.5.1 Overloading Constructors
You can have more than one constructor in a class, as long as each has a different list of
arguments.

Example:
class rectangle {
float height;
float width;
rectangle(float, float){ // constructor
…}
rectangle(){ // another constructor
…}
void draw(); // draw member function
void move(int, int); // move member function
}
3.4 Composition
Composition is a relationship existing between two objects. It is a condition in which an object
uses another object within its definition. The relationship between the two is called
composition.

Composition has a ‘has-a’ relationships and represents an ownership relationship between two
objects.

Example:

public class Name {



}

public class Student {

Name studentName

}

In the above two classes, it is shown that a Student class uses an object of type Name within
its definition. Such a relationship is what we say composition.

3.5 The static and final keywords

3.5.1 The static keyword

A static keyword is used to makes a member i.e. a variable or a method to be a class member.
Thus the member will be shared among all objects of the class and it is no more confined to a
specific.

• Static variables: static variables have class scope. A class’s public static members can be
accessed through a reference to any object of the class, or they can be accessed by qualifying
the member name with the class name and a dot (.). A class’s private static class members can
be accessed only through methods of the class.

• A method declared static cannot access non-static class members, because a static methodcan
be called even when no objects of the class have been instantiated.

• The this reference cannot be used in a static method.


Note that static variables and methods are accessed using Class while instance
variables are accessed using Objects.

Example:
public class AccessingFieldsExample{
static int value1;
int value2;
}
In this simplified example if we have an instance object object1 i.e.
AccessingFieldsExample object1;
Then the following accessing ways for the variables defined within the class definition are
right:
AccessingFieldsExample.value1;
object1.value2;
But it is a mistake to use the following ways:
AccessingFieldsExample.value2;
object1.value1;
3.5.2 The final keyword
final keyword in Variables

• Keyword final specifies that a variable is not modifiable—in other words, it is constant.
Constants can be initialized when they are declared or by each of a class’s constructors. If a
final variable is not initialized, a compilation error occurs.

final keyword in Methods

A method that is declared final in a superclass cannot be overridden in a subclass. Methods that
are declared private are implicitly final, because it is impossible to override them in a subclass.

Methods that are declared static are also implicitly final.

final keyword in classes

A class that is declared final cannot be a superclass (i.e., a class cannot extend a final class).
All methods in a final class are implicitly final.
Example: Class String is an example of a final class. This class cannot be extended, so programs
that use Strings can rely on the functionality of String objects as specified in the Java API.

Can you give a naïve explain how final keyword can be used in security.

3.6 Constructors and Destructors


3.6.1 Constructors
It is a member function which initializes a class. A constructor has:
(i) the same name as the class itself
(ii) no return type
• A constructor is called automatically whenever a new instance of a class is created.
• If you do not specify a constructor, the compiler generates a default constructor for you
(expects no parameters and has an empty body).

3.6.2 Destructors
It is a member function which deletes an object. A destructor function is called automatically
when the object goes out of scope:

(1) the function ends


(2) the program ends
(3) a block containing temporary variables ends
(4) a delete operator is called
A destructor has:
(i) the same name as the class but is preceded by a tilde (~)
(ii) no arguments and return no values
If you do not specify a destructor, the compiler generates a default destructor for you.
When a class contains a pointer to memory you allocate, it is your responsibility to
release the memory before the class instance is destroyed.

Self-review exercise
1. (Rectangle Class) Create a class Rectangle. The class has attributes length and width,
each of which defaults to 1. It has methods that calculate the perimeter and the area of
the rectangle. It has set and get methods for both length and width. The set methods
should verify that length and width are each floating-point numbers larger than 0.0 and
less than 20.0. Write a program to test class Rectangle.
2. (Tic-Tac-Toe) Create a class TicTacToe that will enable you to write a complete
program to play the game of Tic-Tac-Toe. The class contains a private 3-by-3 two-
dimensional array of integers. The constructor should initialize the empty board to all
zeros. Allow two human players. Wherever the first player moves, place a 1 in the
specified square, and place a 2 wherever the second player moves. Each move must be
to an empty square. After each move, determine whether the game has been won and
whether it is a draw. If you feel ambitious, modify your program so that the computer
makes the moves for one of the players. Also, allow the player to specify whether he or
she wants to go first or second. If you feel exceptionally ambitious, develop a program
that will play three-dimensional Tic-Tac-Toe on a 4-by-4-by-4 board [Note: This is a
challenging project that could take many weeks of effort!].
Chapter Four
Inheritance

Objectives: the main objective of learning inheritance is to develop efficient programs avoiding
unnecessary code duplications. Completing this chapter, you are expected to:

4.1. Explain what Inheritance is


4.2. Explain and work with Super classes and Subclasses
4.3. Understand and explain protected members
Creating programs of real-world problems using constructors in Subclasses

4.1 Introduction to Inheritance


Inheritance is another fundamental object-oriented technique. It is a mechanism of organizing
and creating reusable classes. Inheritance allows a class to use the data members and methods
from another class.

4.1.1 Advantages of Inheritance:

 Application development time will be less


 Redundancy of code is reduced. Hence we can get consistence of the program and less
memory
 Investment cost towards the project is reduced.
 On overall the performance of the application is improved.

4.1.2 Reusable Techniques / Inheritance types:


In order to reuse the data members and methods from one class to another class, in Java we
have the following types of inheritances.

Single Inheritance:
Single Inheritance is one, in which there exists single base class and single derived class.
Multilevel Inheritance:

Multilevel Inheritance is one in which there exists single base class and single derived class
and n no. of intermediate base classes. (Intermediate base class is one in which there exists a
single class in one context it act as base class and in another context it is acting as derived
class).

Hierarchical Inheritance:
Hierarchical Inheritance is one in which there exists single base class and n no. of derived
classes.

Multiple Inheritances: [not supported by java]


Multiple Inheritance is one in which there exists multiple base classes and single derived class.
Hybrid Inheritance: [not supported by java]

Hybrid Inheritance is a combination of any java available inheritance. In the combination one
of them is multiple inheritances which is not supported by the Java through classes.

4.2 Super classes and Subclasses:


4.2.1 Superclass

The class which is giving data members and methods is known as Base class or super class/
parent class.
4.2.2 Subclass

The class which is taking data members and methods from the base class or super class is
known as sub class or derived class/child class. The process of inheritance is also known as
sub classing/extendable class/reusable class/derivation.
4.2.3 UML diagram of Inheritance

Vehicle Superclass

Car Subclass

Fig 1: UML diagram of inheritance

4.2.4 Deriving Subclasses

In Java, we use the reserved word extends to establish an inheritance relationship

Example: The way a new Car class inherits the members of an existing Vehicle class

class Car extends Vehicle


{
// class contents
}

4.3 The protected member

Visibility modifier determine which class members are inherited and which are not

• Variables and methods declared with public visibility are inherited; those with private
visibility are not
• But public variables violate the principle of encapsulation
• There is a third visibility modifier that helps in inheritance situations: protected

The protected modifier allows a member of a base class to be inherited into a child. Protected
visibility provides more encapsulation than public visibility does. However, protected visibility
is not as tightly encapsulated as private visibility
4.4 Constructors in Subclasses

A child’s constructor shall necessarily call the parent’s constructor. The first line of a child’s
constructor should use the super reference to call the parent’s constructor. The super reference
can also be used to reference other variables and methods defined in the parent’s class.

The keyword super is responsible for calling the superclass members.

Example: class Car extends Vehicle


{
super(); // calls the superclasses’s constructor
}

Self-review exercise
1. Write an inheritance hierarchy for classes Quadrilateral, Trapezoid, Parallelogram,
Rectangle and Square. Use Quadrilateral as the superclass of the hierarchy. Make the
hierarchy as deep (i.e., as many levels) as possible. Specify the instance variables and
methods for each class. The private instance variables of Quadrilateral should be the x-y
coordinate pairs for the four endpoints of the Quadrilateral. Write a program that
instantiates objects of your classes and outputs each object’s area (except Quadrilateral).
2. Draw an inheritance hierarchy for students at a university similar to the hierarchy shown
in above Figures. Use Student as the superclass of the hierarchy, then extend Student with
classes UndergraduateStudent and GraduateStudent. Continue to extend the hierarchy as
deep (i.e., as many levels) as possible. For example, Freshman, Sophomore, Junior and
Senior might extend UndergraduateStudent, and DoctoralStudent and MastersStudent
might be subclasses of GraduateStudent. After drawing the hierarchy, discuss the
relationships that exist between the classes. [Note: You do not need to write any code for
this exercise.]
CHAPTER 5
POLYMORPHISM
Polymorphism: “The ability of a variable or argument to refer at run-time to instances
of various classes”
When a program invokes a method through a super class variable, the correct subclass version
of the method is called, based on the type of the reference stored in the super class variable.

The same method name and signature can cause different actions to occur, depending on the
type of object on which the method is invoked.

In computer science the term polymorphism means “a method the same as another in spelling
but with different behavior.” The computer differentiates between (or among) methods
depending on either the method signature (after compile) or the object reference (at run time).

Polymorphic Example
In the example below polymorphism is demonstrated by the use of multiple add methods. The
computer differentiates among them by the method signatures (the list of parameters: their
number, their types, and the order of the types.)

This form of polymorphism is called early-binding (or compile-time) polymorphism because


the computer knows after the compile to the byte code which of the add methods it will execute.
That is, after the compile process when the code is now in byte-code form, the computer will
“know” which of the add methods it will execute. If there are two actual int parameters the
computer will know to execute the add method with two formal int parameters, and so on.
Methods whose headings differ in the number and type of formal parameters are said to be
overloaded methods. The parameter list that differentiates one method from another is said to
be the method signature list.

There is another form of polymorphism called late-binding (or run-time) polymorphism


because the computer does not know at compile time which of the methods are to be executed.
It will not know that until “run time.” Run-time polymorphism is achieved through what are
called overridden methods (while compile-time polymorphism is achieved with overloaded
methods). Run-time polymorphism comes in two different forms: run-time polymorphism with
abstract base classes and run-time polymorphism with interfaces. Sometimes run-time
polymorphism is referred to as dynamic binding.

ABSTRACT CLASS
An abstract class is a class with an abstract method.

 An abstract method is method without a body, i.e., only declared but not defined.

 It is not possible to make instances of abstract classes.

 Abstract method are defined in subclasses of the abstract class.

Abstract classes

 Classes those are too general to create real objects

 Used only as abstract super classes for concrete subclasses and to declare reference
variables

 Many inheritance hierarchies have abstract super classes occupying the top few levels

 Keyword abstract

 Use to declare a class abstract

 Also use to declare a method abstract

 Abstract classes normally contain one or more abstract methods

 All concrete subclasses must override all inherited abstract methods

Abstract Class and Method, Example

• Classes with abstract methods must declared abstract.

• Classes without abstract methods can be declared abstract.

• A subclass to a concrete superclass can be abstract.


• Constructors can be defined on abstract classes.

• Instances of abstract classes cannot be made.

• Abstract fields not possible

abstract class ClassName


{
// <class body>
}

Following concepts demonstrate different types of polymorphism in java.

1) Method Overloading
2) Method Overriding
Method Definition:
A method is a set of code which is referred to by name and can be called (invoked) at any
point in a program simply by utilizing the method’s name.
1 )Method Overloading:

In Java, it is possible to define two or more methods of same name in a class, provided that
there argument list or parameters are different. This concept is known as Method Overloading.

1) Method Overloading
1. To call an overloaded method in Java, it is must to use the type and/or number of
arguments to determine which version of the overloaded method to actually call.

2. Overloaded methods may have different return types; the return type alone is
insufficient to distinguish two versions of a method. .

3. When Java encounters a call to an overloaded method, it simply executes the version
of the method whose parameters match the arguments used in the call.

4. It allows the user to achieve compile time polymorphism.

5. An overloaded method can throw different exceptions.

6. It can have different access modifiers.

Rules for Method Overloading


1. Overloading can take place in the same class or in its sub-class.

2. Constructor in Java can be overloaded

3. Overloaded methods must have a different argument list.

4. Overloaded method should always be the part of the same class (can also take place in
sub class), with same name but different parameters.

5. The parameters may differ in their type or number, or in both.

6. They may have the same or different return types.

7. It is also known as compile time polymorphism.

2) Method Overriding
Child class has the same method as of base class. In such cases child class overrides the parent
class method without even touching the source code of the base class. This feature is known as
method overriding.
Rules for Method Overriding:

1. applies only to inherited methods

2. object type (NOT reference variable type) determines which overridden method will
be used at runtime

3. Overriding method can have different return type (refer this)

4. Overriding method must not have more restrictive access modifier

5. Abstract methods must be overridden

6. Static and final methods cannot be overridden

7. Constructors cannot be overridden

8. It is also known as Runtime polymorphism.

super keyword in Overriding:


When invoking a superclass version of an overridden method the super keyword is used.
Example:

class Vehicle { public void move () {


[Link] ("Vehicles are used for moving from one place to another "); }
}
class Car extends Vehicle { public void move () {
super. move (); // invokes the super class method
[Link] ("Car is a good medium of transport ");
}
}
public class TestCar {
public static void main (String args []){
Vehicle b = new Car (); // Vehicle reference but Car object
[Link] (); //Calls the method in Car class
}
}
Output:
Vehicles are used for moving from one place to another
Car is a good medium of transport

Self-review exercise
1. Create a payroll system to include an additional Employee subclass PieceWorker that
represents an employee whose pay is based on the number of pieces of merchandise
produced. Class PieceWorker should contain private instance variables wage (to store the
employee’s wage per piece) and pieces (to store the number of piecesproduced). Provide a
concrete implementation of method earnings in class PieceWorker that calculates the
employee’s earnings by multiplying the number of pieces produced by the wage per piece.
Create an array of Employee variables to store references to objects of each concrete class
in the new Employee hierarchy. For each Employee, display its string representation and
earnings.
CHAPTER 6

EXCEPTION HANDLING
Introduction
Errors are the wrongs that can make a program go wrong. An error in a program is called bug.
Removing errors from program is called debugging. Error messages are classified into two
types.

 Compile time errors


 Runtime errors

Compile time errors


All syntax errors will be detected and displayed by the java compiler, so it is called as Compile
time error. Whenever compile time error occurs java compiler doesn’t create .class file. The
most common compile time errors are as follows
 Missing semi colon ;
 miss match of ( )
 miss spelling of identifiers or keywords
 missing “ in strings
 usage of undeclared variables

Runtime errors/Logical Errors:


A program may compile successfully creating the .class file, but may not run properly such
program may result wrong due to the wrong logic. Most common runtime errors are as follows

 dividing an integer by zero


 accessing an element that is out of bounds of array
 passing a parameter that is not in a valid range or value for a method etc.

Exception: An abnormal event in a program is called Exception. An exception is a condition


that is caused by a runtime error in the program when the java interpreter encounters an error
such as dividing an int by zero. It creates an exception object and throws, if u want to continue
program with execution of remaining code then we should try to catch the exception thrown
by the error condition and display an appropriate message for correct it. This task is known as
Exception Handling, which performs the following
 Find the problem (hit the exception)
 Inform that an error has occurred (throw the exception)
 Receive the error information (catch the exception)
 Take corrective actions (handle the exception)

Exception may occur at compile time or at runtime. Exceptions which occur at compile time
are called “Checked Exceptions”. Exceptions which occur at run time are called “Unchecked
Exceptions”.
Object: Object is a super class of all classes (user defined, pre-defined classes) directly or
indirectly. Because it is included in the lang package.
Throwable: Throwable is super class of errors and exceptions in java. Throwable is deriving
from the object class.
Error: Error is a class. This is not handled. We know the error in program after the compilation
denoted by the java compiler. Always these were detected at compile time.

Checked Exceptions:
 A checked exception is any subclass of Exception (or Exception itself), excluding class
Run time Exception and its subclasses.
 You should compulsorily handle the checked exceptions in your code, otherwise your
code will not be compiled. i.e. you should put the code which may cause checked
exception in try block. "checked" means they will be checked at compile time itself.
 There are two ways to handle checked exceptions. You may declare the exception using
a throws clause or you may use the try...catch block.
 The most perfect example of Checked Exceptions is IO Exception which should be
handled in your code compulsorily or else your code will throw a Compilation Error.

Ex:
ClassNotFoundException
NoSuchMethodException
NoSuchFieldException
SQLException
IOException etc..,
Exception Hierarchy:

Unchecked Exceptions:
 Unchecked exceptions are run time exceptions including Run time Exception and any
of its subclasses. Class Error and its subclasses also are unchecked.
 Unchecked runtime exceptions represent conditions that, generally speaking, reflect
errors in your program's logic and cannot be reasonably recovered from at run time.
 With an unchecked exception, however, compiler doesn't force client programmers
either to catch the exception or declare it in a throws clause.

The most Common examples are

ArrayIndexOutOfBoundsException
NUllPointerException
ClassCastException
ArithmeticException
NumberFormatException etc..

Exception Handling:
Java exception handling is managed via by five keywords: try, catch, throw, throws, and
finally.
try: The try block is said to govern the statements enclosed within it and defines the scope of
any exception associated with it. It detects the exceptions.

catch: The catch block contains a series of legal Java statements. These statements are executed
if and when the exception handler is invoked. It holds an exception.

throw: To manually throw an exception, use the keyword throw.

throws: Any exception that is thrown out of a method must be specified as such by a throws
clause.

finally: Any code that absolutely must be executed after a try block completes is put in a finally
block. After the exception handler has run, the runtime system passes control to the finally
block.

Sy: try
{
Block of code;
}
catch(Exception obj) or catch(Exception-name obj)
{
Block of handle code;
}

Note:
A java program may have multiple catch blocks, like cases in switch statement, but should have
only one try block.
Sy:
1. try{
……….
……….
}
finally{
……….
………..
}
2. try{
……….
……….
}
catch(ArithmaticExeption e)
{
………
………
}
catch(Exception e)
{
………
………
}
finally
{
……….
………..
}

Advantages of Exceptions:
Using exceptions to manage errors has some advantages over traditional errormanagement
Techniques
1. Separating Error-Handling Code from "Regular" Code
2. Propagating Errors Up the Call Stack
3. Grouping and Differentiating Error Types

You might also like