0% found this document useful (0 votes)
58 views82 pages

Java

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 82

Chapter 1

Introduction to Object-Oriented Programming (OOP)


Objectives
After you have read and studied this chapter, you should be able to: -
 Differentiate procedural Programming and OOP.
 Name the basic components of object-oriented programming
 Differentiate classes and objects.
 Describe significance of inheritance in object-oriented programs.

Programming paradigms
There are different types of programming languages, such as:
Procedural Programming: is a list of instructions telling a computer,
step-by-step, what to do, usually having a linear order of execution from
the first statement to the second and so forth with occasional loops and
branches. Procedural programming language includes C, FORTRAN,
Pascal, and Basic.
Procedural languages are characterized by sequential sets of linear
commands. The focus of such languages is on structure.
Object oriented programming: allow the programmer to break down the
problem into objects: self-contained entities consisting of both data and
operations on the data. E.g. java, C#, VB.NET
•The focus of OOP languages is not on structure, but on modeling data.

Advantage of OOPs over Procedure-oriented programming language


1) OOPs makes development and maintenance easier where as in Procedure-oriented
programming language it is not easy to manage if code grows as project size grows.
2) OOPs provides data hiding whereas in Procedure-oriented programming language
a global data can be accessed from anywhere.
3) OOPs provides ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented
Programming.language.

1.1. Overview of Object Oriented Programming


The OO paradigm aims to eliminate some of the flaws of the procedural
approach to programming. In OO, data is critical – data is not allowed to
move freely around a system, but it is tied closely to the functions that
operate on it. Data is also protected from unintentional modification by
other functions.
In OO programming, a system or problem is decomposed into entities
called objects. An object has data members and functions – in Java,
functions are known as methods.
Data is protected because the data belonging to an object can only be
accessed and modified by the methods of that object.
Different objects can 'talk' to each other through their methods – in this
way, Object A cannot directly modify data belonging to Object B – but it
can call a method of Object B that in turn modifies the data.

Object means a real word entity such as pen, chair, table etc.
Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software development
and maintenance by providing some core concepts:
 Class
 Object
 Encapsulation
 Inheritance
 Abstraction
 Polymorphism

To summarise the OOP approach:


 Emphasis on data, not procedure
 Programs are made up of objects
 The data structures reflect characteristics of the objects
 Methods that operate on the data of an object are tied into the data
structure
 Data is hidden from external functions
 Objects can communicate with each other through methods
 New data and methods can be easily added when necessary
 Takes a bottom-up approach to program design
1.2. Classes and Objects
 Object-oriented programs use objects.
 Objects are the basic runtime entities in an OO program. An object:
oIs an identifiable thing or individual?
oIs of significance to the system
oHas characteristic behaviour (i.e. functionality)
oHas states reflected in the attributes (data) held about the object.
A class is the definition of a set of objects which are all similar in terms of
their attributes, associations and functionality e.g. customer class defines
all customer objects.

Methods can be public or private.


Public methods:
oAre triggered by receipt of a message from another object
oHave a public interface
oCan be defined at the class or object level
oCan be inherited (see Inheritance below)
Private methods:
oAre triggered by methods within an object
oAre internal to a class
oCan be changed without affecting any methods outside the
class
A class is a bit like a data-type – once a class has been defined, any number
of objects belonging to that class can be created. The objects then are a bit
like variables – each object is associated with the class type from which it
was created.

Technical contrast between Objects & Classes

CLASS OBJECT
Class is a data type Object is an instance of Class.
It generates OBJECTS It gives life to CLASS
Does not occupy memory It occupies memory location.
location
It cannot be manipulated because it is not It can be manipulated.
available in memory (except static class)

1.3. Data Abstraction and Encapsulation


Encapsulation means the wrapping up of data and methods into a single
unit (a class). It also means that the data inside a class is hidden from
everything outside the class.
 The data can only be accessed by invoking the methods of the class.
The internal workings of the methods are of no concern to other
classes in the program.
 Information Hiding.
 Implementation can change without effecting any calling code.
 The class is kind of a container or capsule or a cell, which
encapsulate the set of methods, attributes and properties to provide
its indented functionalities to other classes.

Abstraction refers to the way in which a class represents only the essential
features of the set of objects it models – a class does not include
background or extra details that are not relevant to the system.
So a class is like a list of abstract attributes e.g. size, weight, cost, and the
methods that operate on those attributes e.g. change the cost, increase the
weight.
 Hiding internal details and showing functionality is known as
abstraction. For example: phone call, we don't know the internal
processing.
 Is the process of removing characteristics from something in order to
reduce it to a set of essential characteristics.
1.4 Inheritance
Inheritance is the way in which objects of one class get the properties of
objects of another class. This includes the data and the methods.
For example, take a system in which there are various types of 'person'
objects – they have some attributes in common, such as Name, Address
and Date of Birth. The person that is an Employee is part of the class
'Person', but has some extra attributes such as Salary, Department and Rank.
 On the surface, inheritance is a code re-use issue. we can extend code
that is already written in a manageable manner.
Benefits of Inheritance
 Used to avoid redundancy.
 Useful for easy modification (modification can be made only
once)
 New classes can be easily added (sometimes may require
restructuring)
 Used to generalize/specialize classes
1.4. Polymorphism

 The word polymorphism means the ability to take more than one
form. In terms of the OOP, this means that a particular operation may
behave differently for different sub-classes of the same class.
 Consider a class hierarchy for different shapes. A Shape class
encapsulates the common features of shapes – such as drawing a
shape and calculating the area of a shape (or, in other words, each
Shape object can draw itself and can calculate its area).
 Deals with the ability of an object to be of different forms.
 Polymorphism comes in the form that a reference in an OO program
can refer to objects of different types at different times
1.5. Java Technology
What is Java Technology?
 The Java technology is:
 A programming language
 A development environment
 An application environment
 A deployment environment
 A programming language
o As a programming language, Java can create all kinds of
applications that you could create using any conventional
programming language.
 A Development Environment
o As a development environment, Java technology provides you
with a large suite of tools:
 A compiler (javac)
 An interpreter (java)
 A documentation generator (javadoc)
 A class file packaging tool and so on...
 An Application and Runtime Environment
 Java technology applications are typically general-purpose
programs that run on any machine where the Java runtime
environment (JRE) is installed.
 Deployment Environment
 The JRE supplied by the Java 2 Software Development Kit
(SDK) contains the complete set of class files for all the Java
technology packages, which includes basic language classes,
GUI component classes, and so on.

Key features of Java technology…


Java Features…
 Java Virtual Machine (JVM)
 an imaginary machine that is implemented by emulating
software on a real machine
 provides the hardware platform specifications to which you
compile all Java technology code
 Bytecode
 a special machine language that can be understood by the Java
Virtual Machine (JVM).
 Independent of any computer hardware, so any computer with a
Java interpreter can execute the compiled Java program, no
matter what type of computer the program was compiled on.
 Garbage collection thread
 responsible for freeing any memory that can be freed.
 This happens automatically during the lifetime of the Java
program.
 programmer is freed from the burden of having to deallocate that
memory themselves
 Code Security
 Code security is attained in Java through the implementation of its
Java Runtime Environment (JRE).
 JRE runs code compiled for a JVM and performs class loading
(through the class loader), code verification (through the bytecode
verifier) and finally code execution.
 class files are loaded into memory on demand, as needed by the
program.
 The class responsible for finding and loading class files into
memory at run time is called Class Loader.
 It adds security by separating the namespaces for the classes of
the local file system from those that are imported from network
sources.
About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity - Java is case sensitive, which means identifier Hello and
hello would have different meaning in Java
 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. When saving the file, you should save it using the class name
(Remember Java is case sensitive) and append '.java' to the end of the name (if
the file name and the class name do not match your program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name, then the file should
be saved as'MyFirstJavaProgram.java'
 public static void main(String args[]) - Java program processing starts from
the main() method, which is a mandatory part of every Java program. Java
Identifiers: All Java components require names. Names used for classes,
variables and methods are called identifiers. In Java, there are several points to
remember about identifiers. They are as follows: 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. Examples of legal identifiers: age, $salary, _value, __1_value
Chapter – 2
2. Basics in Java Programming
Java Identifiers:
All Java components requires names. Names used for classes, variables
and methods are called identifiers. In Java, there are several points to
remember about identifiers. They are as follows: 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. Examples of legal identifiers: age,
$salary, _value, __1_value.
Defining Classes
In Java, a program is made up of a main class and any other classes needed
to support the main class.
A class is defined via the class keyword and the name of the class. Simple
Syntax
modifier class ClassName
{
// body of the class
}
Example
public class Student
{
//body of the class
}

 By convention, all class names in Java begin with a capital letter and
capitalize the first letter of each word they include (e.g.,
SampleClassName).
 A Java class name is an identifier—a series of characters consisting of
letters, digits, underscores ( _ ) and dollar signs ($) that does not begin
with a digit and does not contain spaces.
 Cannot contain Java Reserved keywords
Java Reserved Keywords:
The following list shows the reserved words in Java. These reserved words
may not be used as constant or variable or any other identifier names.
abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implements import
instanceof int interface long native
new package private protected public
return short static strictfp super
switch Synchronized this throw throws
transient Try void volatile while

 A class can contain any of the following


 Data types
 Property or attribute or Variables
o Characteristics of certain object.
 Method
o an action performed by an object (a verb)
 Constructor
o Is a method used to invoke the class with data or used to create
an object from class
 Access Modifiers
o Public: means that any class can access the Variables/methods
o Protected: means that only the class and its subclasses can
access the variables/methods.
o Private: means that only the class can access the
Variables/methods

Java Data Types


Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in the
memory. Based on the data type of a variable, the operating system
allocates memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can store
integers, decimals, or characters in these variables.
There are two data types available in Java −
 Primitive Data Types
 Reference/Object Data Types
Primitive Data Types
There are eight primitive datatypes supported by Java. Primitive datatypes
are predefined by the language and named by a keyword. Let us now look
into the eight primitive data types in detail.

Primitive Data Types:

Data Type Size Range


byte 1 byte Integers in the range of -128 to +128
short 2 bytes Integers in the range of -32,768 to +32,767
int 4 bytes Integers in the range of -2,147,483,648 to +2,147,483,647
long 8 bytes Integers in the range of -9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
float 4 bytes Floating-point numbers in the range of ±3.4x10-38 to ±3.4x1038
with 7 digits of accuracy
double 8 bytes Floating-point numbers in the range of ±1.7x10-308 to
±1.7x10308 with 15 digits of accuracy
boolean true and This data type is used for simple flags that track true/false
false conditions
char used to har data type is a single 16-bit Unicode character
store any Eg character ‘A’
character

Reference Data Types:

Reference variables are created using defined constructors of the classes.


They are used to access objects. These variables are declared to be of a
specific type that cannot be changed. For example, Employee, Puppy,
etc.
 Class objects and various types of array variables come under
reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the
declared type or any compatible type.
 Example: Animal animal = new Animal("giraffe");
Java Literals:

A literal is a source code representation of a fixed value. They are


represented directly in the code without any computation. Literals can
be assigned to any primitive type variable. For example:

String literals in Java are specified like they are in most other languages
by enclosing a sequence of characters between a pair of double quotes.
Examples of string literals are:
"Hello
World"
"two\n
lines"
"\"This is in quotes\""

Variables
A variable provides us with named storage that our programs can
manipulate. Each variable in Java has a specific type, which determines
the size and layout of the variable's memory; the range of values that can
be stored within that memory; and the set of operations that can be
applied to the variable.
Three types of Variables in Java
Local variables
Declared in methods and includes method parameter
Not accessible outside the methods and don’t get default value.
Instance variables
Declared within the class and Represent Object State
Gets default value and cannot be reinitialized within the class
Class variables (Static Variable)
Declared within the class and Represent Object State
Shared between different object of the same class.
Gets default value and cannot be reinitialized within the class
Local variables:
 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block
is entered, and the variable will be destroyed once it exits the
method, constructor or block.
 Access modifiers cannot be used for local variables.

 Local variables are visible only within the declared method,


constructor or block.
 Local variables are implemented at stack level internally.
 There is no default value for local variables so local variables
should be declared and an initial value should be assigned before
the first use.
Example:
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to
this method only.
public class Test{
public void pupAge() {
int age = 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {

Test test = new Test();

test.pupAge();
}
}

This would produce the following result:


Puppy age is: 7

Instance variables:
 Instance variables are declared in a class, but outside a method,
constructor or any block.
 When a space is allocated for an object in the heap, a slot for each
instance variable value is created.
 Instance variables are created when an object is created with the use
of the keyword 'new' and destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than
one method, constructor or block, or essential parts of an object's
state that must be present throughout the class.
 Instance variables can be declared in class level before or after use.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and
block in the class. Normally, it is recommended to make these
variables private (access level). However visibility for subclasses
can be given for these variables with the use of access modifiers.
 Instance variables have default values. For numbers the default
value is 0, for Booleans it is false and for object references it is null.
Values can be assigned during the declaration or within the
constructor.
 Instance variables can be accessed directly by calling the variable
name inside the class. However within static methods and different
class ( when instance variables are given accessibility) should be
called using the fully qualified name .
ObjectReference.VariableName.
Example:
import java.io.*; public
class Employee{
// salary variable is visible in Employee class only. private
double salary;
// The name variable is assigned in the constructor. public
Employee (String empName){
name = empName;
}
// The salary variable is assigned a value. public
void setSalary(double empSal){ salary = empSal;
}
// This method prints the employee details. public void
printEmp(){ System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]){ Employee
empOne = new Employee("Ransika");
empOne.setSalary(1000); empOne.printEmp();
}
}

This would produce the following result:


name : Ransika
salary :1000.0

Class/static variables:
 Class variables also known as static variables are declared with the static
 keyword in a class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
 Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final and static.
Constant variables never change from their initial value.
 Static variables are stored in static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the
program stops.
 Visibility is like instance variables. However, most static variables are
declared public since they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value
is 0; for Booleans, it is false; and for object references, it is null. Values can
be assigned during the declaration or within the constructor. Additionally
values can be assigned in special static initializer blocks.
 Static variables can be accessed by calling with the class name .
ClassName.VariableName.
 When declaring class variables as public static final, then variables names
(constants) are all in upper case. If the static variables are not public and

final the naming syntax is the same as instance and local variables.
Example:

import java.io.*; public class


Employee{

// salary variable is a private static variable private static


double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development "; public
static void main(String args[]){

salary = 1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
}
}
This would produce the following result:
Development average salary:1000
Note: If the variables are access from an outside class the constant should be accessed as
Employee.DEPARTMENT

Variables and Data Types


 A variable is a place where information can be stored while a
program is running.
 The value can be changed at any point in the program—hence the
name
 To create a variable, you must give it a name and identify what type
of information it will store.
 You also can give a variable an initial value at the same time you
create it.

21
Variable Declaration
<Data type> [variable name][=Row data or expression]
The type of information is listed first, followed by the name of the variable.
The following are all examples of variable declarations:
int loanLength; boolean gameOver;
If you are creating several variables of the same type, you can declare
all of them in the same statement by separating the variable names
with commas.
String street, city, state;
Naming Variables
 Variable names in Java must start with a letter, an underscore
character (“_”), or a dollar sign (“$”).
 They cannot start with a number.
 After the first character, variable names can include any combination
of letters or numbers.
 it’s important to remember that Java is case sensitive
 Rule of thumb
o The first letter of the variable name is lowercase.
o Each successive word in the variable name begins with a capital
letter.
o All other letters are lowercase.
Assigning Values to Variables
 After a variable has been declared, a value can be assigned to it with
the assignment operator, which is an equal sign (“=”).
 The following are examples of assignment statements:
o idCode = 8675309;
o accountOverdrawn = false;
Methods
Methods define an object’s behavior—that is, anything that happens when
the object is created as well as the various tasks the object can perform
during its lifetime.
Defining Methods
In Java, a method definition has four basic parts:
 The name of the method
 A list of parameters
 The type of object or primitive type returned by the
method
22
 The body of the method

Here’s what a basic method definition looks like:


modifier returnType methodName(type1 arg1, type2 arg2, type3 arg3 ...)
{
// body of the method
}

The returnType is the primitive type or class of the value returned by the
method.
It can be one of the primitive types, a class name, or void if the
method does not return a value at all.
The method’s parameter list is a set of variable declarations separated by
commas and set inside parentheses.
These parameters become local variables in the body of the method,
receiving their values when the method is called.
Constructor
 A class contains constructors that are invoked to create objects from
the class blueprint.
 Constructor declarations look like method declarations—except that
they use the name of the class and have no return type. For example,
Student class may have one or more constructor(s):
The this keyword
Within an instance method or a constructor, this is a reference to the
current object — the object whose method or constructor is being called.
You can refer to any member of the current object from within an instance
method or a constructor by using this.
Using this with a Field
The most common reason for using the this keyword is because a field is
shadowed by a method or constructor parameter.

Java Operator
 An operator is a symbol that operates on one or more arguments to
produce a result.
 Java provides a rich set of operators to manipulate variables.
23
 TYPES OF OPERATORS
 Assignment Operators
 Increment Decrement Operators
 Arithmetic Operators
 Bitwise Operators
 Relational Operators
 Logical Operators
 Ternary Operators
 Comma Operators
 Instance of Operators

1. ASSIGNMENT OPERATORS
o The assignment statements has the following syntax:
<variable> = <expression>

2. INCREMENT AND DECREMENT OPERATORS ++ AND - -


 The increment and decrement operators add an integer variable by
one.
 increment operator: two successive plus signs, ++
 decrement operator: two successive minus signs –
Common Shorthand

24
a=a+ 1; a++; or ++a;

a=a- 1; a--; or --a;

3. ARITHMETIC OPERATORS
 The arithmetic operators are used to construct mathematical
expressions as in algebra.
 Their operands are of numeric type.

Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement

4. BITWISE OPERATORS
 Java's bitwise operators operate on individual bits of integer (int and
long) values.

25
 If an operand is shorter than an int, it is promoted to int before doing
the operations.

Operator Name Description

a&b and 1 if both bits are 1.

a|b or 1 if either bit is 1.

a^b xor 1 if both bits are different.

~a not Inverts the bits.


n << p left shift Shifts the bits of n left p positions.
Zero bits are shifted into the low-order
positions.
n >> p right shift Shifts the bits of n right p positions. If
n is a 2's complement signed number,
the sign bit is shifted into the high-
order positions.
n >>> p right shift Shifts the bits of n right p positions.
Zeros are shifted into the high-order
positions.

EXAMPLE OF BITWISE OPERATORS


class Test {
public static void main(String args[]) { int a = 60; /* 60 = 0011 1100 */
26
int b = 13; /* 13 = 0000 1101 */ int c = 0;
c = a & b; /* 12 = 0000 1100 */ System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */ System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */ Output: a & b = 12
System.out.println("~a = " + c ); a | b = 61
c = a << 2; /* 240 = 1111 0000 */ a ^ b = 49
System.out.println("a << 2 = " + c );
~a = -61
c = a >> 2; /* 215 = 1111 */
a << 2 = 240
System.out.println("a >> 2 = " + c );
a >> 15 a >>> 15
c = a >>> 2; /* 215 = 0000 1111 */
System.out.println("a >>> 2 = " + c );

5. RELATIONAL OPERATORS
 A relational operator compares two values and determines the
relationship between them.
 For example, != returns true if its two operands are unequal.
 Relational operators are used to test whether two values are equal,
whether one value is greater than another, and so forth.

< Checks if the value of left operand is less than


the value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater
than or equal to the value of right operand, if
27
yes then condition becomes true.
<= Checks if the value of left operand is less than or
equal to the value of right operand, if yes then
condition becomes true.
public LessThanExample
{
public static void main(String args[])
{
int a = 5; int b = 10; if(a < b)
{
System.out.println("a is less than b");
}
}
}
6. LOGICAL OPERATORS
 These logical operators work only on boolean operands. Their return
values are always boolean.
Operator Description
&& Called Logical AND operator. If both the operands
are non zero then then condition becomes true.
|| Called Logical OR Operator. If any of the two
operands are non zero then then condition becomes
true.
! Called Logical NOT Operator. Use to reverses the
logical state of its operand. If a condition is true
then Logical NOT operator will make false.
EXAMPLE OF LOGICAL OPERATORS
public class ANDOperatorExample{
public static void main(String[] args){ char ans = 'y';
int count = 1;
if(ans == 'y' & count == 0){
28
System.out.println("Count is Zero.");} if(ans == 'y' & count == 1) {
System.out.println("Count is One."); }
if(ans == 'y' & count == 2) {
System.out.println("Count is Two.");
}}}
7. TERNARY OPERATORS
 Java has a short hand way by using ?: the ternary conditional
operator for doing ifs that compute a value.

// longhand with if:


int answer;
if ( a > b )
{
answer = 1;
}
else
{
answer = -1;
}
// can be written more tersely with the ternary operator as: int answer
= a > b ? 1 : -1;
8. COMMA OPERATORS
 Java has an often look past feature within it’s for loop and this is the
comma operator.
 Usually when people think about commas in the java language they
think of a way to split up arguments within a functions parameters.
public class CommaOperator {
public static void main(String[] args) {
for(int i = 1, j = i + 10; i < 5; i++, j = i * 2) {
System.out.println("i= " + i + " j= " + j);
}
}
}
9. INSTANCEOF OPERATORS
29
 This operator is used only for object reference variables. The operator
checks whether the object is of a particular type(class type or
interface type).
 InstanceOf operator is wriiten as:
( Object reference variable ) instanceOf (class/interface type)

class Vehicle {}
public class Car extends Vehicle
{
public static void main(String args[])
{
Vehicle a = new Car();
boolean result =
a instanceof Car; System.out.println( result);
}
}

Chapter – 3
Conditional Statement, Repetition Statement and Array
2.1 Decision and Repetition Statements
The Java keywords for controlling program flow are nearly identical to C++. This is
one of the most obvious ways in which Java shows its legacy as a derivative of this
language. In this section, you will see how to use Java's control flow statements.
2.1.1. Decision / Conditional Statements / Selection Statment
The Java language provides two alternative statements -if statements and switch
statements - for selecting among the given alternatives.
The if Statement
The Java if statement is a test of any Boolean expression. If the Boolean expression
evaluates to true, the statement following the if statement is executed. On the other
hand, if the Boolean expression evaluates to false, the statement following the if is not
executed. For example, consider the following code fragment:
30
import java.util.Date;

Date today = new Date();

if (today.getDay == 0) then

System.out.println("It is Sunday.");

This code uses the java.util.Date package and creates a variable named today that will
hold the current date. The getDay member method is then applied to today and the
result compared to 0. A return value of 0 for getDay indicates that the day is Sunday,
so if the Boolean expression today.getDay = = 0 is true, a message is displayed. If today
isn't Sunday, no action occurs. In Java, the expression used within an if statement
must evaluate to a Boolean.
The Java developers included an else statement that can be executed whenever an if

statement evaluates to false. This can be seen in the following sample code:
import java.util.Date;

Date today = new Date();

if (today.getDay == 0) then

System.out.println("It is Sunday.");

else

System.out.println("It is NOT Sunday.");

In this case, the same message will be displayed whenever it is Sunday, but a different
message will be displayed whenever it is not Sunday. Both examples so far have only
shown the execution of a single statement within the if or the else cases. By enclosing
the statements within curly braces, you can execute as many lines of code as you'd
like. This can be seen in the following example that makes some suggestions about
how to spend each day of the week:

31
import java.util.Date;

Date today = new Date();

if (today.getDay == 0) then {

System.out.println("It is Sunday.");

System.out.println("And a good day for golf.");

else {

System.out.println("It is NOT Sunday.");

System.out.println("But still a good day for golf.");

Because it's possible to execute whatever code you desire in the else portion of an
if…else block, you may have already reasoned that it is possible to execute another if
statement inside the else statement of the first if statement. This is commonly known
as an if…else if…else block, an example of which follows:
import java.util.Date;

Date today = new Date();

if (today.getDay == 0) then

System.out.println("It is Sunday.");

else if (today.getDay == 1) then

System.out.println("It is Monday.");

else if (today.getDay == 2) then

System.out.println("It is Tuesday.");

else if (today.getDay == 3) then

System.out.println("It is Wednesday.");

32
else if (today.getDay == 4) then

System.out.println("It is Thursday.");

else if (today.getDay == 5) then

System.out.println("It is Friday.");

else

System.out.println("It must be Saturday.");

The switch Statement


As you can see from the previous code sample, a lengthy series of if…else if…else
statements can get complicated and hard to read as the number of cases increases.
Fortunately, you can avoid this problem by using Java's switch statement. The Java
switch statement is ideal for testing a single expression against a series of possible
values and executing the code associated with the matching case statement, as shown
in the following example:
import java.util.Date;

Date today = new Date();

switch (today.getDay) {

case 0: // Sunday

System.out.println("It is Sunday.");

break;

case 1: // Monday

System.out.println("It is Monday.");

break;

case 2: // Tuesday

System.out.println("It is Tuesday.");

break;
33
case 3: // Wednesday

System.out.println("It is Wednesday.");

break;

case 4: // Thursday

System.out.println("It is Thursday.");

break;

case 5: // Friday

System.out.println("It is Friday.");

System.out.println("Have a nice weekend!");

break;

default: // Saturday

System.out.println("It must be Saturday.");

System.out.println("All done!");

You should have noticed that each day has its own case within the switch. The
Saturday case (where today.getDay = 6) is not explicitly given but is instead handled by
the default case. Any switch block may include an optional default case that will
handle any values not caught by an explicit case.
Within each case, there can be multiple lines of code. The block of code that will
execute for the Friday case, for example, contains three lines. The first two lines will
simply display informational messages, but the third is a break statement. The
keyword break is used within a case statement to indicate that the flow of the program
should move to the first line following the switch block. In this example, break appears
as the last statement in each case except the default and will cause program execution

34
to move to the line that prints "All done!" The break statement was left out of the
default block because by that point in the code, the switch block was ending, and there
was no point in using an explicit command to exit the switch.
If, as the previous example seems to imply, you always need to include a break

statement at the end of each block, why not just leave break out and have Java assume
that after a block executes, control should move outside the switch block? The answer
is that there are times when you do not want to break out of the switch statement after
executing the code for a specific case value. For example, consider the following code
that could be used as a scheduling system for physicians:
import java.util.Date;

Date today = new Date();

switch (today.getDay) {

case 0: // Sunday

case 3: // Wednesday

case 6: // Saturday

System.out.println("It's Golf Day!");

break;

case 2: // Tuesday

System.out.println("Tennis at 8:00 am");

case 1: // Monday

case 4: // Thursday

case 5: // Friday

System.out.println("Office Hours: 10:00 - 5:00");

break;

35
}

System.out.println("All done!");

This example illustrates a couple of key concepts about switch statements. First, you'll
notice that it is possible to have multiple cases execute the same block of code, as
follows:
case 0: // Sunday

case 3: // Wednesday

case 6: // Saturday

System.out.println("It's Golf Day!");

break;

This code will result in the message "It's Golf Day" being displayed if the current day
is Wednesday, Saturday, or Sunday. If you collect the three cases together without
any intervening break statements, each will execute the same code. But consider what
happens on Tuesday when the following code executes:
case 2: // Tuesday

System.out.println("Tennis at 8:00 am");

Certainly a reminder about the message match will be displayed, but this case doesn't
end with a break statement. Because Tuesday's code doesn't end with a break statement,
the program will continue executing the code in the following cases until a break is
encountered. This means that Tuesday's code flows into the code used for Monday,
Thursday, and Friday as shown in the following:
case 2: // Tuesday

System.out.println("Tennis at 8:00 am");

case 1: // Monday

case 4: // Thursday
36
case 5: // Friday

System.out.println("Office Hours: 10:00 - 5:00");

break;

This will result in the following messages being displayed every Tuesday:
Tennis at 8:00 am

Office Hours: 10:00 - 5:00

On Monday, Thursday, and Friday, only the latter message will display.
In addition to writing switch statements that use integer cases, you can use character
values as shown in the following example:

The following rules apply to a switch statement:

 The variable used in a switch statement can only be a byte, short, int, or char.

 You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.

 The value for a case must be the same data type as the variable in the switch and it must be a
constant or a literal.

 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.

 When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.

 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.

 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case

Iteration
37
Iteration is an important concept in any computer language. Without the ability to
loop or iterate through a set of values, our ability to solve real-world problems would
be severely limited. Java's iteration statements are nearly identical to those found in C
and C++ and include for loops, while loops, and do…while loop

38
The for Statement
The first line of a for loop enables you to specify a starting value for a loop counter,
specify the test condition that will exit the loop, and indicate how the loop counter
should be incremented (decremented) after each pass through the loop. The syntax of
a Java for statement is as follows:
for (initialization; testExpression; incremement)

statement

For example, a sample for loop may appear as follows:


int count;

for (count=0; count<100; count++)

System.out.println("count = " + count);

In this example, the initialization statement of the for loop sets count to 0. The test
expression, count < 100, indicates that the loop should continue as long as count is less
than 100. Finally, the increment statement increases the value of count by one. As long
as the test expression is true, the statement following the for loop setup will be
executed, as follows:
System.out.println("count = " + count);

Of course, you probably need to do more than one thing inside the loop. This is as
easy to do as using curly braces to indicate the scope of the for loop, as shown in the
following:
int count;

for (count=0; count<100; count++) {

YourMethod(count);

39
System.out.println("Count = " + count);

One nice shortcut that can be taken with a Java for loop is to declare and initialize the
variable used in the loop. For example, in the following code, the variable count is
declared directly within the for loop:
for (int count=0; count<100; count++)

System.out.println("Count = " + count);

It may look like an unimportant difference whether you declare a variable before a for
loop or within the loop. However, there are advantages to declaring the variable
within the loop. First, it makes your intention to use the variable within the loop clear.
If the variable is declared above the for loop, how will you remember (and how will
future programmers know) that the variable was intended to be used only within the
loop? Second, a variable declared within the for loop will go out of scope at the end of
the loop. This means you could not write the following code:
for (int count=0; count<100; count++)

System.out.println("Count = " + count);

System.out.println("Loop exited with count = " + count);

The last line cannot find a variable named count because count goes out of scope when
the for loop terminates. This means that, in addition to making the intended purpose of
the variable clearer, it is also impossible to accidentally bypass that intent and use the
variable outside the loop.
You can also leave out portions of the first line of a for loop. In the following example,
the increment statement has been left out:

40
for (int count=0; count<100; ) {

count += 2;

System.out.println("Count = " + count);

Of course, leaving the increment statement out of the for loop declaration in this
example doesn't achieve any useful purpose since count is incremented inside the loop.
It is possible to get even fancier with a Java for loop by including multiple statements
or conditions. For example, consider the following code:
for (int up=0, down = 20; up < down; up++, down -= 2 ) {

System.out.println("Up = " + up + "\tDown = " + down);

This loop starts the variable up at 0 and increments it by 1. It also starts the variable
down at 20 and decrements it by 2 for each pass through the loop. The loop continues
until up has been incremented enough that it is equal to or greater than the variable
down.

The test expression portion of a Java for loop can be any Boolean expression. Because
of this, it does not need to be a simple test (x < 10), as shown in the preceding
examples. The test expression can be a method call, a method call combined with a
value test, or anything that can be phrased as a Boolean expression. For example,
suppose you want to write a method that will display a message indicating the first
year since World War II that the Chicago Cubs appeared in the World Series. You
could do this as follows:
The method DidCubsPlayInWorldSeries is passed an integer value indicating the year
and returns a Boolean value that indicates whether or not the Cubs made it to the

41
World Series in that year. This method is an example of the switch statement shown
earlier in this chapter.
The while Statement
Related to the for loop is the while loop. The syntax for a while loop is as follows:
while(booleanExpression){

Body statement

As you can tell from the simplicity of this, the Java while loop does not have the built-
in support for initializing and incrementing variables that its for loop does. Because of
this, you need to be careful to initialize loop counters prior to the loop and increment
them within the body of the while loop. For example, the following code fragment will
display a message five times:
int count = 0;

while (count < 5) {

System.out.println("Count = " + count);

count++;

The do…while Statement


The final looping construct in Java is the do…while loop. The syntax for a do…while

loop is as follows:
do {

statement

} while (booleanExpression);

42
This is similar to a while loop except that a do…while loop is guaranteed to execute at
least once. It is possible that a while loop may not execute at all depending on the test
expression used in the loop. For example, consider the following method:
public void ShowYears(int year) {

while (year < 2000) {

System.out.println("Year is " + year);

year++;

This method is passed a year value, then loops over the year displaying a message as
long as the year is less than 2000. If year starts at 1996, then messages will be
displayed for the years 1996, 1997, 1998, and 1999. However, what happens if year

starts at 2010? Because the initial test, year < 2000, will be false, the while loop will
never be entered. Fortunately, a do…while loop can solve this problem. Because a
do…while loop performs its expression testing after the body of the loop has executed
for each pass, it will always be executed at least once. This is a very valid distinction
between the two types of loop, but it can also be a source of potential errors.
Whenever you use a do…while loop, you should be careful to consider the first pass
through the body of the loop.
Jumping
Of course, it is not always easy to write all of your for, while and do…while loops so
that they are easy to read and yet the loops terminate on exactly the right pass through
the loop. Java makes it easier to jump out of loops and to control other areas of
program flow with its break and continue statements.

43
The break Statement
Earlier in this chapter, you saw how the break statement is used to exit a switch

statement. In a similar manner, break can be used to exit a loop. As an example of this,
consider the following code:
int year = 1909;

while (DidCubsWinTheWorldSeries(year) == false) {

System.out.println("Didn't win in " + year);

if (year >= 3000) {

System.out.println("Time to give up. Go White Sox!");

break;

System.out.println("Loop exited on year " + year);

This example shows a while loop that will continue to execute until it finds a year that
the Chicago Cubs won the World Series. Because they haven't won since 1908 and
the loop counter year starts with 1909, it has a lot of looping to do. For each year they
didn't win, a message is displayed. However, even die-hard Cubs fans will eventually
give up and change allegiances to the Chicago White Sox. In this example, if the year
is 3000 or later, a message is displayed and then a break is encountered. The break

statement will cause program control to move to the first statement after the end of
the while loop. In this case, that will be the following line:
System.out.println("Loop exited on year " + year);

The continue Statement


Just as a break statement can be used to move program control to immediately after
the end of a loop, the continue statement can be used to force program control back to
44
the top of a loop. Suppose you want to write a method that will count and display the
number of times the Cubs have won the World Series this century. One way to do this
would be to first see if the Cubs played in the World Series and then see if they won.
This could be done as follows:

int timesWon = 0;

for (int year=1900; year <= 2000; year++) {

if (DidCubsPlayInWorldSeries(year) = false)

continue;

if (DidCubsWinWorldSeries(year)) {

System.out.println("Cubbies won in " + year + "!");

timesWon++;

System.out.println("The Cubs won " + timesWon + " times.");

In this case, a for loop is used to iterate through the years from 1900 to 2000. The first
line within the loop tests to see if the Cubs played in the World Series. If they didn't,
the continue statement is executed. This moves program control back to the for loop.
At that point, year is incremented and the expression year <= 2000 is retested. If year is
less than or equal to 2000, the loop continues. If, however, DidCubsPlayInWorldSeries

equals true, then the continue statement is skipped, and the next test is performed to
see if the Cubs won that year.
Infinite Loops

 Executing the statements in the body of a while loop must


eventually make the condition false
45
 If not, it is called an infinite loop, which will execute until the user
interrupts the program

 This is a common logical error

 You should always double check the logic of a program to ensure


that your loops will terminate

 An example of an infinite loop:

int count = 1;

while (count <= 25)

System.out.println(count);

count = count - 1;

 This loop will continue executing until the user externally interrupts the
program.
2.2.1. Advanced Arrays

Introduction

• Arrays are data structures consisting of related data items of the


same type.

46
• Arrays are fixed-length entities—they remain the same length once
they are created, although an array variable may be reassigned such
that it refers to a new array of a different length.

 Treated as objects

 Cause:

 Have instance variables (e.g. length)

 Uses keyword new to create the array

 But are not full-fledged objects

 Cause :

 can not be subclassed

 does not inherit any thing form Object class

Declaring arrays

 Arrays are created with keyword new.

 To create an array object, the programmer specifies the type of the


array elements and the number of elements as part of an array-
creation expression that uses keyword new.

 Array variable may be one of the following type:

 Primitive (int, char, long, byte, double, …)

 Reference (String, TextField, Image, …)

47
 Declaring arrays…Syntax

ArrayType[ ] arrayVariable;

 E.g. 1
Int[] count
String[] names;
Double[] marks;
 Creating arrays…Syntax

arrayVariable= new ArrayType[size];

E.g.
count = new int[3]; Creating Array with size 3
names = new String [12];

marks = new double [5];

 Initializing arrays…Syntax
ArrayType arrayVariable[ ]={val1,val2, …, valn};
a comma-separated list of expressions

48
Or, You can use loops to initialized arrays.

int x[]=new int[4];


for (int i=0;i<=3;i++)
{
X[i]=0;
}
 Array elements are automatically initialized to default values that
depend on the element type.
• boolean elements are initialized to false
• integer and real types are initialized to 0.
• reference types that is, arrays of objects are initialized to null.
Arrays … Two Dimentional

Declaring

arrayType arrayVariable[][];

arrayVariable=new arrayType[rowSize][columnSize];

E.g.

int calander[][];

calander=new int[13][30];

49
Size

E.g.

int x[][]=new int[13][30];

int count=x.length;

What will be the value of count?

int n=x[2].length;

What will be the value of n?

 Regarding varieties of methods in array manipulation just refer to

java.util.Arrays

Chapter – 4 OOP Concepts


50
Object & Classes

Java is an Object-Oriented Language. As a language that has the Object


Oriented feature, Java supports the following fundamental concepts:
 Polymorphism
 Inheritance
 Encapsulation
 Abstraction
 Classes
 Objects
 Instance
 Method
In this chapter, we will look into the concepts Classes and Objects.
 Object - Objects have states and behaviors. Example: A dog has states-
color, name, breed as well as behaviors -wagging, barking, 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.

51
Objects in Java:
Let us now look deep into what are objects. If we consider the real-world we can
find many objects around us, Cars, Dogs, Humans, etc. All these objects have a
state and behavior. If we consider a dog, then its state is - name, breed, color, and
the behavior is - barking, wagging, running If you compare the software object
with a real world object, they have very similar characteristics. Software objects
also have a state and behavior. A software object's state is stored in fields and
behavior is shown via methods. So in software development, methods operate on
the internal state of an object and the object- to-object communication is done via
methods.

Classes in Java:
A class is a blue print from which individual objects are created. A sample of a class
is given below:
public class
Dog{ String breed;

int age; String


color; void
barking(){

}
void hungry(){
}
void sleeping(){
}
}
A class can contain any of the following variable types.
 Local variables: Variables defined inside methods, constructors or blocks
52
are called local variables. The variable will be declared and

53
initialized within the method and the variable will be destroyed when the
method has completed.
 Instance variables: Instance variables are variables within a class but
outside any method. These variables are instantiated when the class is loaded.
Instance variables can be accessed from inside any method, constructor or
blocks of that particular class.
 Class variables: Class variables are variables declared within a class,
outside any method, with the static keyword.

A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.
Below mentioned are some of the important topics that need to be discussed when
looking into classes of the Java Language.
Constructors:
When discussing about classes, one of the most important subtopic would be
constructors. Every class has a constructor. If we do not explicitly write a
constructor for a class the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The
main rule of constructors is that they should have the same name as the class. A
class can have more than one constructor.
Example of a constructor is given below:
public class
Puppy{ public
Puppy(){

}
public Puppy(String name){
// This constructor has one parameter, name.

54
}

55
Creating an Object:

As mentioned previously, a class provides the blueprints for objects. So basically


an object is created from a class. In Java the new keyword is used to create new
objects. There are three steps when creating an object from a class:
 Declaration: A variable declaration with a variable name with an object
type.
 Instantiation: The 'new' keyword is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a constructor.
This call initializes the new object.

Example of creating an object is given below:


public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :"+ name );

}
public static void main(String[]args){
// Following statement would create an object myPuppy
Puppy myPuppy =new Puppy("tommy");

}
}

If we compile and run the above program, then it would produce the following result:

Passed Name is: tommy

56
Accessing Instance Variables and Methods:

Instance variables and methods are accessed via created objects. To access an
instance variable the fully qualified path should be as follows:
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();

Example:

This example explains how to access instance variables and methods of a class:

public class
Puppy{ int puppyAge;

public Puppy(String name){


// This constructor has one parameter, name.
System.out.println("Passed Name is :"+ name );

}
public void setAge(int
age ){ puppyAge = age;

}
public int getAge(){
System.out.println("Puppy's age is :"+ puppyAge );
return puppyAge;

71
}
public static void main(String[]args){
/* Object creation *
Puppy myPuppy =newPuppy("tommy");
/* Call class method to set puppy's age */
myPuppy.setAge(2);

/* Call another class method to get puppy's age */


myPuppy.getAge();

/* You can access instance variable as follows as well */


System.out.println("Variable Value :"+ myPuppy.puppyAge );

}
}

If we compile and run the above program, then it would produce the following result:

PassedName is:tommy
Puppy's age is :2
Variable Value :2

72
Source file declaration rules:

As the last part of this section, let‘s now look into the source file declaration rules.
These rules are essential when declaring classes, import statements and package
statements in a source file.
 There can be only one public class per source file.
 A source file can have multiple nonpublic classes.
 The public class name should be the name of the source file as well which
should be appended by .java at the end. For example: The class name is.
public class Employee{} Then the source file should be as Employee.java.

 If the class is defined inside a package, then the package statement should be
the first statement in the source file.
 If import statements are present then they must be written between the
package statement and the class declaration. If there are no package
statements, then the import statement should be the first line in the source
file.
 Import and package statements will imply to all the classes present in the
source file. It is not possible to declare different import and/or package
statements to different classes in the source file.

Classes have several access levels and there are different types of classes;
abstract classes, final classes, etc. I will be explaining about all these in the
access modifiers chapter.

Apart from the above mentioned types of classes, Java also has some special
classes called Inner classes and Anonymous class

73
1. INHERITANCE

Inheritance can be defined as the process where one object acquires the

properties of another. With the use of inheritance, the information is

made manageable in a hierarchical order. When we talk about inheritance,

the most commonly used keyword would be extends and implements.

These words would determine whether one object IS-A type of another.

By using these keywords, we can make one object acquire the properties

of another

Inheritance in java is a mechanism in which one object acquires all the

properties and behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that

are built upon existing classes. When you inherit from an existing class,

you can reuse methods and fields of parent class, and you can add new

methods and fields also.

• One of the most effective features of Oop’s paradigm.


• Establish a link/connectivity between 2 or more classes.
• Permits sharing and accessing properties from one to another class.
• to establish this relation Java uses ‘extends’ keyword.
Why use inheritance in java

For Method Overriding (so runtime polymorphism can be achieved).


For Code Reusability.

74
Syntax of Java Inheritance

class Subclass-name extends Superclass-name

//methods and fields

The extends keyword indicates that you are making a new class that derives

from an existing class.

In the terminology of Java, a class that is inherited is called a super class. The

new class is called a subclass.

class Employee{

float salary=40000;

class Programmer extends Employee{

int bonus=10000;

public static void main(String

args[]){ Programmer p=new

Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer

is:"+p.bonus);

75
}

Output:

Programmer salary is:40000.0

Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class

as well as of Employee class i.e. code reusability.

76
Chapter 5
Category of Classes on the Basis of Inheritance
1. Super class
 (base/parent/driver/inheritance/ ancestor class).
 Top located class
 Service provider (its properties accessed by all its lower level class).

2. Intermediate class
 (mediating/dual class).
 Middle located class
 Having Dual policy (obtain properties of upper level class and transmit properties
to lower level class).

3. Child class
 (sub/associate/derived/inherited class).
 Bottom located class much benefitted class much loaded class
 properties of child class as well as
 class and parent class can beaccessed by
 only the object of child class.
Relation between classes

TYPES of INHERITANCE
1. Single Inheritance
 A structure having one and only one parent as well
as child class.
 Child class is authorized to access the property of parent class

77
Chapter 5

2. Multilevel Inheritance
 Standard structure of Single Inheritance having one Parent, one or more
intermediate and one child classes.
 Child class as well as intermediate class may access the properties of upper level
classes.

3. Hierarchical Inheritance
 A structure having one parent and more child class.
 Child classes must be connected with only Parent class.

78
Chapter 5

Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another by using the
extends keyword. To see how, let’s begin with a short example. The following program
creates a superclass called A and a subclass called B. Notice how the keyword extends is
used to create a subclass of A.
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
79
Chapter 5
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}

class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
80
Chapter 5
}

The output from this program is shown here:


Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
As you can see, the subclass B includes all of the members of its superclass, A. This is why
subOb can access i and j and call showij( ). Also, inside sum( ), i and j can be referred to
directly, as if they were part of B.
Even though A is a superclass for B, it is also a completely independent, stand-alone class.
Being a superclass for a subclass does not mean that the superclass cannot be used by itself.
Further, a subclass can be a superclass for another subclass. The general form of a class
declaration that inherits a superclass is shown here: class subclass-name extends superclass-
name {
// body of class
}
You can only specify one superclass for any subclass that you create. Java does not support
the inheritance of multiple super classes into a single subclass. You can, as stated, create a
hierarchy of inheritance in which a subclass becomes a superclass of another subclass.
However, no class can be a superclass of itself.
2. Polymorphism

Polymorphism is the ability of an object to take on many forms. In programming languages


polymorphism is the capability of an action or method to do different things based on the
object that it is acting upon. This is the third basic principle of object oriented programming.
The two types of polymorphism are: method overloading and Method overriding.
81
Chapter 5
Overloaded methods are methods with the same name signature but either a different number
of parameters or different types in the parameter list. For example 'spinning' a number may
mean increase it, 'spinning' an image may mean rotate it by 90 degrees. By defining a method
for handling each type of parameter you control the desired effect.

Overridden methods are methods that are redefined within an inherited or subclass. They
have the same signature and the subclass definition is used.

Casting Objects

One of the difficulties of using a superclass array to hold many instances of subclass objects
is that one can only access properties and methods that are in the superclass (ie. common to
all). By casting an individual instance to its subclass form, one can refer to any property or
method. But first take care to make sure the cast is valid by using the instanceof operator.
Then perform the cast. As an example using the above Animal class:

if (ref[x] instanceof Dog) // ok right type of object


{
Dog doggy = (Dog) ref[x]; // cast current instance to subclass
doggy.someDogOnlyMethod();
}

Casts to subclass can be done implicitely but explicit casts are recommended. Casts to
superclass must be done explicitly. Casts cannot be made between sibling classes.
Method overloading and method overriding in Java
Method overloading and method overriding uses concept of Polymorphism in Java where
method name remains same in two classes but actual method called by JVM depends upon
object at run time and done by dynamic binding in Java. Java supports both overloading and
overriding of methods. In case of overloading method signature changes while in case of
overriding method signature remains same and binding and invocation of method is decided
on runtime based on actual object. This facility allows Java programmer to write very
flexibly and maintainable code using interfaces without worrying about concrete
implementation. One disadvantage of using Polymorphism in code is that while reading code
you don't know the actual type which annoys while you are looking to find bugs or trying to
debug program. But if you do Java debugging in IDE you will definitely be able to see the
actual object and the method call and variable associated with it.
Method Overriding

82
Chapter 5
In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within a subclass, it will always refer
to the version of that method defined by the subclass. The version of the method defined by
the superclass will be hidden. Consider the following:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
83
Chapter 5
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown here:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used. That is, the version of show( ) inside B overrides the version declared in A. If you wish
to access the superclass version of an overridden method, you can do so by using super. For
example, in this version of B, the superclass version of show( ) is invoked within the
subclass’ version. This allows all instance variables to be displayed.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the following
output:
i and j: 1 2
k: 3
84
Chapter 5
Here, super.show( ) calls the superclass version of show( ).
Method overriding occurs only when the names and the type signatures of the two methods
are identical. If they are not, then the two methods are simply overloaded. For example,
consider this modified version of the preceding example:
// Methods with differing type signatures are overloaded – not
// overridden.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// overload show()
void show(String msg) {
System.out.println(msg + k);
}
85
Chapter 5
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B

subOb.show(); // this calls show() in A


}
}
The output produced by this program is shown here:
This is k: 3
i and j: 1 2
The version of show( ) in B takes a string parameter. This makes its type signature different
from the one in A, which takes no parameters. Therefore, no overriding (or name hiding)
takes place. Instead, the version of show( ) in B simply overloads the version of show( ) in A.
Applying Method Overriding
Let’s look at a more practical example that uses method overriding. The following program
creates a superclass called Figure that stores the dimensions of a two-dimensional object. It
also defines a method called area( ) that computes the area of an object. The program derives
two subclasses from Figure. The first is Rectangle and the second is Triangle. Each of these
subclasses overrides area( ) so that it returns the area of a rectangle and a triangle,
respectively.
// Using run-time polymorphism.
class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
86
Chapter 5
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class FindAreas {
87
Chapter 5
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
The output from the program is shown here:
Inside Area for Rectangle.
Area is 45
Inside Area for Triangle.
Area is 40
Area for Figure is undefined.
Area is 0
Through the dual mechanisms of inheritance and run-time polymorphism, it is possible to
define one consistent interface that is used by several different, yet related, types of objects.
In this case, if an object is derived from Figure, then its area can be obtained by calling
area( ). The interface to this operation is the same no matter what type of figure is being
used.

88
Chapter 5

89
90
91
92
93
94
95
96
97
98
99
1

You might also like