Java Programming Module
Java Programming Module
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
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.
Key Differences
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.
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.
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!)
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.
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:
Example: C, C++
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.
Java Disadvantages
• Running byte code through the interpreter is not as fast as running machine code, which
is specific to that platform.
• 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
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:
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.
datatype variableName;
Examples of variable declarations:
If variables are of the same type, they can be declared together, as follows:
double radius,area;
Example: int i;
i = 10;
Variables can be declared and initialized in one step.
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.
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.
⚫ 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.
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.
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:
Example
Two types:
The if Statements
The switch Statement
• 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:
Construct:
if (expression) {
// if expression returns true, the statement(s) in this block are
executed
}
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
}
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
}
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.
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 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.
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
default:
default_statement;
break;
}
While
do-while
for
for-each
The code block in the while loop may not be executed at all
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!
datatype[] label;
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.
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:
Example:
Output: 5
Important: Arrays are always of the same size: their lengths cannot be changed once they are
Created!
Example:
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:
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.
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.
3.1.1 Objects
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.
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:
// list of Methods
}
Example:
Example:
public class TestCircle1 {
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:
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.
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:
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.
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.
The date class contains important methods to use for various applications. Please see why and
how such methods are used.
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:
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:
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.
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.
The String class provides the methods for obtaining length, retrieving individual characters,
and concatenating strings; length(), charAt(i: int) and concat(s: String) respectively.
A substring can be extracted from a string using the following two substring method in the
String class.
Example:
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:
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.
To call a method, the name of the method followed shall be specified with a list of comma
separated arguments in parentheses:
If the method has no arguments, the method name shall be written followed with empty
parentheses:
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:
class Factorial {
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:
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.
NB: It is a mistake to try to overload methods just by varying the return type.
Example:
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”.
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:
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.
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.
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.
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.
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.2 Destructors
It is a member function which deletes an object. A destructor function is called automatically
when the object goes out of scope:
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:
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.
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.
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
Example: The way a new Car class inherits the members of an existing Vehicle class
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.
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.)
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.
Abstract classes
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
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. Overloaded method should always be the part of the same class (can also take place in
sub class), with same name but different parameters.
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:
2. object type (NOT reference variable type) determines which overridden method will
be used at runtime
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.
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.
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.
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