Вы находитесь на странице: 1из 60

OOP concepts - Data abstraction, encapsulation, inheritance, benefits of inheritance,

polymorphism, classes and objects, Procedural and object oriented programming


paradigms.
Java programming - History of Java – Basics[comments - data types- variables-
constants- scope and life time of variables- operators- operator hierarchy- expressions-
type conversion and casting, enumerated types-conditional statements- loops- break
and continue statements- simple java stand-alone programs- arrays- console input and
output- formatting output.

Object Oriented Programming Concepts

Object Oriented Programming is a paradigm that provides many concepts such


as inheritance, data binding, polymorphism etc.

Simula is considered as the first object-oriented programming language. The programming


paradigm where everything is represented as an object is known as truly object-oriented
programming language.

Smalltalk is considered as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)

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 concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object Oriented Programming

1
Object
Object: is a bundle of related variables and functions (also known methods).
Objects share two characteristics: They have State and Behavior.
State: State is a well-defined condition of an item. A state captures the relevant aspects of an
object
Behavior: Behavior is the observable effects of an operation or event,
Examples:
eg1:
Object:House
State:Current Location,Color, Area of House etc.
Behavior: Close/Open main door.
eg 2:
Object: – Car
State: Color, Make
Behavior: Climb Uphill, Accelerate, Slowdown etc

Note: Everything a software object knows (State) and can do (Behavior) is represented by
variables and methods (functions) in the object respectively.

There are three main features of OOPS.


1) Encapsulation
2) Inheritance
3) Polymorphism

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation. It
also means hiding data and methods within an Object. For example: capsule, it is wrapped with
different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

.
2
Encapsulation provides the security that keeps data and methods safe from inadvertent
changes. Programmers sometimes refer to encapsulation as using a “black box,” or a device
that you can use without regard to the internal mechanisms.
A programmer can access and use the methods and data contained in the black box but cannot
change them.

Inheritance

An important feature of object-oriented programs is inheritance—the ability to create classes


that shares the attributes and methods of existing classes, but with more specific features.

Inheritance is mainly used for code reusability. So you are making use of already written the
classes and further extending on that. In general, when one object acquires all the properties
and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used
to achieve runtime polymorphism.

Polymorphism
In Core, Java Polymorphism is one easy concept to understand.Polymorphism definition is that
Poly means many and morphs’ means forms. When one task is performed by different ways i.e.
known as polymorphism.
It describes the feature of languages that allows the same word or symbol to be interpreted
correctly in different situations based on the context. There are two types of Polymorphism
available in Java.

For example, in English, the verb “run” means different things if you use it with “a footrace,” a
“business,” or “a computer.” You understand the meaning of “run” based on the other words
used with it. Object-oriented programs are written so that the methods having the same name
works differently in different context. Java provides two ways to implement polymorphism.

Static Polymorphism (compile time polymorphism/ Method overloading):


The ability to execute different method implementations by altering the argument used with the
method name is known as method overloading. In a program, we have three print methods
each with different arguments. When you properly overload a method, you can call it providing
different argument lists, and the appropriate version of the method executes.

3
Dynamic Polymorphism (run time polymorphism/ Method Overriding):
When you create a subclass by extending an existing class, the new subclass contains data
and methods that were defined in the original superclass. In other words, any child class object
has all the attributes of its parent. Sometimes, however, the superclass data fields and methods
are not entirely appropriate for the subclass objects; in these cases, you want to override the
parent class members in order to invoke them.

Abstraction

All programming languages provide abstractions.In java, we use abstract class and interface to
achieve abstractionHiding internal details and showing functionality is known as abstraction.
For example: phone call, we don't know the internal processing.

An essential element of object-oriented programming is an abstraction. Humans manage


complexity through abstraction. When you drive your car you do not have to be concerned with
the exact internal working of your car (unless you are a mechanic). What you are concerned
with is interacting with your car via its interfaces like steering wheel, brake pedal, accelerator
pedal etc. Various manufacturers of car have different implementation of the car working but its
basic interface has not changed (i.e. you still use the steering wheel, brake pedal, accelerator
pedal etc. to interact with your car). Hence the knowledge you have of your car is abstract.

A powerful way to manage abstraction is through the use of hierarchical classifications. This
allows you to layer the semantics of complex systems, breaking them into more manageable
pieces. From the outside, a car is a single object. Once inside, you see that the car consists of
several subsystems: steering, brakes, sound system, seat belts, heating, cellular phone, and so
on. In turn, each of these subsystems is made up of more specialized units. For instance, the
sound system consists of a radio, a CD player, and/or a tape player. The point is that you
manage the complexity of the car (or any other complex system)through the use of hierarchical
abstractions.

An abstract class is something which is incomplete and you cannot create an instance of the
abstract class. If you want to use it you need to make it complete or concrete by extending it. A
class is called concrete if it does not contain any abstract method and implements all abstract
method inherited from abstract class or interface it has implemented or extended.By the way,

4
Java has a concept of abstract classes, abstract method but a variable cannot be abstract in
Java.

Advantage of OOPs over Procedure-Oriented Programming language


1)OOPs make development and maintenance easier whereas in Procedure-oriented
programming language it is not easy to manage if code grows as project size grows.
2)OOPs provide data hiding whereas in Procedure-oriented programming language a global
data can be accessed from anywhere.
3)OOPs provide 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.

HISTORY OF JAVA
• JAVA is language that has evolved from C++ which is a direct descendant of C. Most of
the characters of JAVA is inherited from C and C++.
Derives its Syntax from C.
Object oriented features influenced by C++.
• Java was conceived by James Gosling (popularly known as “Creator of Java”), Patrick
Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc.in
1991.
• It took 18 months to develop the first working version. This was initially named “Oak” but
was renamed as “JAVA” in 1995.
• JAVA is platform independent programming language, which provides developers with
the means to create powerful applications
• Although the Java programming language is usually associated with World Wide Web,
its primary motivation was to develop a language which is platform - independent(i.e.,
architecture neutral) that could be used to create software to be embedded in various
consumer electronic devices, such as microwave ovens and remote controls.
Reasons Which Led To JAVA Language Development
To create software to be embedded in various consumer electronic devices many CPUs are
used as controllers. The problem with C and C++ is that they are designed to be compiled for
aspecifictarget.
Even though C++ programs can be developed for any type of CPU, to do so it requires a full
C++ compiler targeted for that CPU. The problem here is compilers are expensive and time
5
consuming to create.
To overcome this the work began on developing a portable, platform-independent
language that could be used to produce code that run on a variety of CPUs under differing
environments, which led to the creation of JAVA.
World Wide Web also took shape at the same time Java was implemented. With the
emergence of WWW, Java was propelled to the forefront of computer language design,
because the Web also demanded portable programs.
Why Java was Successful?
JAVA was designed, tested and refined by real, working programmers.
1. JAVA is cohesive and logically consistent.
2. JAVA gives the programmer, full control. It’s a language for professional
programmers.
JAVA BYTECODE
• Byte code is a highly optimized set of instructions designed to be executed by the
Java run-time system, which is called the Java Virtual Machine (JVM).
• JVM is an Interpreter for Byte code.
THE JAVA VIRTUAL MACHINE
The JVM is a virtual computer that resides in memory only.
Translating a program into byte code makes it easier to run a program in a wide
variety of environments.
Reason: Only the JVM needed to be implemented for each platform.
The Java programs are compiled for the JVM is what makes the language so
unique but in order for java programs to run on a particular platform, the JVM must
be implemented for that platform.
The JVM is the reason why Java is Portable. It provides a layer of Abstraction
between the compiled Java Program and the underlying hardware platform and
operating system.
JAVA TECHNOLOGY IS BOTH A PROGRAMMING LANGUAGE AND A PLATFORM.
JAVA PROGRAMMING LANGAUGE
With most programming languages, you either compile or interpret a program so
that you can run it on your computer. The Java programming language is unusual in
that a program is both compiled and interpreted.

6
With the compiler, first you translate a program into an intermediate language called
Java bytecodes —the platform-independent codes interpreted by the interpreter on
the Java platform. The interpreter parses and runs each Java bytecode instruction
on the computer.
Compilation happens just once; interpretation occurs each time the program is
executed.
The following figure illustrates how this works.

You can think of Java bytecodes as the machine code instructions for the Java Virtual
Machine (Java VM). Every Java interpreter, whether it's a development tool or a Web
browser that can run applets, is an implementation of the Java VM.
Java bytecodes help make "write once, run anywhere" possible. You can compile your
program into bytecodes on any platform that has a Java compiler. The bytecodes can
then be run on any implementation of the Java VM. That means that as long as a
computer has a Java VM, the same program written in the Java programming language
can run on Windows 2000, a Solaris workstation, or on an iMac.

THE JAVA PLATFORM


A platform is the hardware or software environment in which a program runs. We've
already mentioned some of the most popular platforms like Windows 2000, Linux,
Solaris, and MacOS. Most platforms can be described as a combination of the
operating system and hardware.

7
The Java platform differs from most other platforms in that it's a software-only
platform that runs on top of other hardware-based platforms.
The Java platform has two components:
1. The Java Virtual Machine (Java VM) -- (Already exaplained)
2. The Java Application Programming Interface (Java API)
The Java API is a large collection of ready-made software componentsthat provide many useful
capabilities, such as graphical user interface(GUI) widgets.
The Java API is grouped into libraries of related classes and interfaces; these libraries
are known as packages.
The following figure depicts a program that's running on the Java platform. As the
figure shows, the Java API and the virtual machine insulate the program from the
hardware.

Native code is code that after you compile it, the compiled code runs on a specific
hardware platform. As a platform-independent environment, the Java platform can
be a bit slower than native code. However, smart compilers, well-tuned interpreters,
and just-in-time byte code compilers can bring performance close to that of native
code without threatening portability.
JAVA BUZZWORDS
The Java programming language is a high-level language that can be characterized by all of
the following buzzwords:
 Simple  Architecture neutral
 Object oriented  Portable
 Distributed  High performance

 Interpreted  Multithreaded

 Robust  Dynamic

 Secure

8
IMPLEMENTING A JAVA PROGRAM
Implementation of a Java application program consists of series of steps.

1. Create a source file. A source file contains text, written in the Java programming
language, that you and other programmers can understand. You can use any text editor
to create and edit source files.
Save the source code file with .java extension.

2. Compile the source file into a byte code file. The compiler, javac, takes your source file
and translates its text into instructions that the Java Virtual Machine (Java VM) can
understand. The compiler converts these instructions into a byte code file.
To compile the program, run java compiler with the name of the source file in command
line:
javac <filename>.java

3. Run the program contained in the byte code file. The Java interpreter installed on your
computer implements the Java VM. This interpreter takes your byte code file and
carries out the instructions by translating them into instructions that your computer can
understand. At the command prompt to run a stand-alone Java Program, use java
interpreter, type :
java <filename>
When executed the program displays the output.
Where, <filename> -- user defined filename.
JAVA PROGRAM STRUCTURE
Java Program may contain many classes of which only one class defines the main method.
A Java Program may contain one or more sections.

Documentation Section
Package Statement
Import Statements
Interface Statements
Class Definitions

9
Main Method Calss
{
Main Method Definition
}

Of the above Sections shown in the figure, the Main Method class is Essential part,
Documentation Section is a suggested part and all the other parts are optional.
Documentation Section
It Comprises a Set of comment lines giving the name of the program, the author and
other details.
Comments help in Maintaining the Program.
Java uses a Style of comment called documentation comment.
/* * …… */
This type of comment helps is generating the documentation automatically.
Package Statement
The first statement allowed in a Java file is a package statement. It declares the
package name and informs the compiler that the classes defined belong to this
package.
Example:
package student;
It is an optional declaration.
Import Statements
The statement instructs the interpreter to load a class contained in a particular
package.
Example : import student.test;
Where, student is the package and test is the class.
Interface Statements
An interface is similar to classes which consist of group of method declaration.
It is used when we want to implement the feature of Multiple Inheritance in Java
It is an optional declaration.
Class Definitions
A Java Program can have any number of class declarations.

10
The number of classes depends on the complexity of the program.
Main Method Class
Every Java Stand-alone program requires a main method as its starting point.
A Simple Java Program will contain only the main method class.
It creates objects of various classes and uses those objects for performing various
operations.
When the end of main is reached the program terminates and the control
transferred back to the Operating system.
VARIABLES
A Variable is a named piece of memory that is used for storing data in java Program.
An object stores its state in variables.
A variable is an identifier used for storing a data value.
Definition: A variable is an item of data named by an identifier.
A Variable may take different values at different times during the execution if the program,
unlike the constants.
We must explicitly provide a name and a type for each variable you want to use in your
program. The variable's name must be a legal identifier --an unlimited series of Unicode
characters that begins with a letter. You use the variable name to refer to the data that the
variable contains.
The variable's type determines what values it can hold and what operations can be
performed on it.
General form of variable declaration :
type name

In addition to the name and type that you explicitly give a variable, a variable has scope.
Example of Variable names :
average
height
total height
classStrength
Rules followed for variable names ( consist of alphabets, digits, underscore and dollar
characters)

11
1. They must not begin with digits.
2. Uppercase and lowercase are not the same. Example: Total and total are two variables
which are distinct.
3. It should not be a keyword.
4. Whitespace is not allowed.
5. Variable names can be of any length.
EXAMPLE PROGRAM
The MaxVariablesDemo program, shown below, declares eight variables of different types
within its main method. The variable declarations are bold:
public class MaxVariablesDemo {
public static void main(String args[]) {
// integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;
// real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
// other primitive types
char aChar = 'S';
boolean aBoolean = true;
// display them all
System.out.println("The largest byte value is " + largestByte);
System.out.println("The largest short value is " + largestShort);
System.out.println("The largest integer value is " + largestInteger);
System.out.println("The largest long value is " + largestLong);
System.out.println("The largest float value is " + largestFloat);
System.out.println("The largest double value is " + largestDouble);
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + " is upper case.");
} else {

12
System.out.println("The character " + aChar + " is lower case.");
}
System.out.println("The value of a Boolean is " + aBoolean);
}
}
OUTPUT
The largest byte value is 127
The largest short value is 32767
The largest integer value is 2147483647
The largest long value is 9223372036854775807
The largest float value is 3.40282e+38
The largest double value is 1.79769e+308
The character S is upper case.
The value of a Boolean is true
SCOPE AND LIFETIME OF VARIABLES
Java allows variables to be declared in any block. A block defines a scope.
Each time when we start a new block we are starting a new scope.
Scope determines what objects are visible to other parts of the program and
also determines the lifetime of those objects.
Two major scopes in Java are
Defined by a class.
Defined by a method.
The Scope defined by a method begins with its opening curly brace. As a
general rule, a variable declared inside a scope are not visible to the code that
is defined outside the scope.
Final Variables
o You can declare a variable in any scope to be final. The value of a final variable
cannot change after it has been initialized. Such variables are similar to
constants in other programming languages.
o To declare a final variable, use the final keyword in the variable declaration
before the type:
final int aFinalVar = 0;

13
o The previous statement declares a final variable and initializes it, all at once.
Subsequent attempts to assign a value to aFinalVar result in a compiler error.
o A final local variable that has been declared but not yet initialized is called a
blank final. Again, once a final local variable has been initialized, it cannot be
set, and any later attempts to assign a value to blank final result in a compile-
time error.
DATA TYPES
Every variable must have a data type. A variable's data type determines the values that the
variable can contain and the operations that can be performed on it.
Data types in Java are of two types:
1. Primitive Types( Intrinsic or built-in types )
2. Derived Types (Reference Types).
The following table lists, by keyword, all of the primitive data types supported by the
Java platform, their sizes and formats.

Primitive Data Types

Keyword Description Size/Format

(integers)

byte Byte-length integer 8-bit two's complement

short Short integer 16-bit two's complement

int Integer 32-bit two's complement

long Long integer 64-bit two's complement

(real numbers)

float Single-precision floating point 32-bit IEEE 754

double Double-precision floating 64-bit IEEE 754

14
point

(other types)

16-bit Unicode
char A single character
character

A boolean value (true or


boolean true or false
false)

Arrays, classes, and interfaces are reference types. The value of a reference type variable,
in contrast to that of a primitive type, is a reference to (an address of) the value or set of
values represented by the variable.
A reference is called a pointer or a memory address in other languages. The Java
programming language does not support the explicit use of addresses like other languages
do. You use the variable's name instead.

OPERATORS
Operators are used in programs for manipulating data and variables.
An operator performs a function on one, two, or three operands.
An operator that requires one operand is called a unary operator.
For example, ++ is a unary operator that increments the value of its operand by 1.
An operator that requires two operands is a binary operator.
For example, = is a binary operator that assigns the value from its right-hand operand to its
left-hand operand.
A ternary operator is one that requires three operands. The Java programming language
has one ternary operator?:
The various categories of operators are as follows:

• Arithmetic Operators
• Relational and Conditional Operators
• Shift and Logical Operators

15
• Assignment Operators
• Other Operators

♦ Arithmetic Operators
The following table lists the basic arithmetic operators provided by the Java
programming language. Except for +, which is also used to concatenate strings, these
operators can be used only on numeric values.

Binary Arithmetic Operators

Operator Use Description

Adds op1 and op2; also used to


+ op1 + op2
concatenate strings

- op1 - op2 Subtracts op2 from op1

* op1 * op2 Multiplies op1 by op2

/ op1 / op2 Divides op1 by op2

Computes the remainder of dividing op1 by


% op1 % op2
op2

These short cut operators increment or decrement a number by one.

Shortcut Arithmetic Operators

Operator Use Description

++ op++ Increments op by 1; evaluates to the value of op before it was incremented

++ ++op Increments op by 1; evaluates to the value of op after it was incremented

-- op-- Decrements op by 1; evaluates to the value of op before it was decremented

-- --op Decrements op by 1; evaluates to the value of op after it was decremented

Other arithmetic operators of Java programming language.

16
Unary Arithmetic Operators

Operator Use Description

Promotes op to int if it's a byte, short, or


+ +op
char

- -op Arithmetically negates op

Relational and Conditional Operators


Use these relational operators to determine the relationship between two values.

Relational Operators

Operator Use Description

> op1 > op2 Returns true if op1 is greater than op2

>= op1 >= op2 Returns true if op1 is greater than or equal to op2

< op1 < op2 Returns true if op1 is less than op2

<= op1 <= op2 Returns true if op1 is less than or equal to op2

== op1 == op2 Returns true if op1 and op2 are equal

!= op1 != op2 Returns true if op1 and op2 are not equal

You can use the following conditional operators to form multi-part decisions.

Conditional Operators

Operator Use Description

&& op1 && op2 Returns true if op1 and op2 are both true; conditionally evaluates op2

|| op1 || op2 Returns true if either op1 or op2 is true; conditionally evaluates op2

! !op Returns true if op is false

& op1 & op2 Returns true if op1 and op2 are both boolean and both true; always

17
evaluates op1 and op2; if both operands are numbers, performs
bitwise AND operation

Returns true if both op1 and op2 are boolean and either op1 or op2 is
| op1 | op2 true; always evaluates op1 and op2; if both operands are numbers,
performs bitwise inclusive OR operation

Returns true if op1 and op2 are different — that is, if one or the other
^ op1 ^ op2
of the operands, but not both, is true

♦ Shift and Logical Operators


Each shift operator shifts the bits of the left-hand operand over by the number of positions
indicated by the right-hand operand.
The shift occurs in the direction indicated by the operator itself.

Shift Operators

Operator Use Description

Shift bits of op1 left by distance op2; fills with zero bits on the right-
<< op1 << op2
hand side

Shift bits of op1 right by distance op2; fills with highest (sign) bit on
>> op1 >> op2
the left-hand side

Shift bits of op1 right by distance op2; fills with zero bits on the left-
>>> op1 >>> op2
hand side

These operators perform logical functions on their operands.

Logical Operators

Operator Use Operation

& op1 & op2 Bitwise AND if both operands are numbers;

18
conditional AND if both operands are boolean

Bitwise OR if both operands are numbers;


| op1 | op2
conditional OR if both operands are boolean

^ op1 ^ op2 Bitwise exclusive OR (XOR)

~ ~op2 Bitwise complement

♦ Assignment Operators
The basic assignment operator looks as follows and assigns the value of op2 to op1.
op1 = op2;

In addition to the basic assignment operation, the Java programming language defines these
short cut assignment operators that perform an operation and an assignment using one
operator.

Shortcut Assignment Operators

Operator Use Equivalent to

+= op1 += op2 op1 = op1 + op2

-= op1 -= op2 op1 = op1 - op2

*= op1 *= op2 op1 = op1 * op2

/= op1 /= op2 op1 = op1 / op2

%= op1 %= op2 op1 = op1 % op2

&= op1 &= op2 op1 = op1 & op2

|= op1 |= op2 op1 = op1 | op2

^= op1 ^= op2 op1 = op1 ^ op2

<<= op1 <<= op2 op1 = op1 << op2

>>= op1 >>= op2 op1 = op1 >> op2

19
>>>= op1 >>>= op2 op1 = op1 >>> op2

♦ Summary of Other Operators

The Java programming language also supports these operators.

Other Operators

Operator Use Description

op1 ? op2 :
?: If op1 is true, returns op2. Otherwise, returns op3.
op3

Declares an array of unknown length, which contains


[] type []
typeelements.

Creates and array with op1 elements. Must be used with the new
[] type[ op1 ]
operator.

Accesses the element at op2 index within the array op1. Indices
[] op1[ op2 ]
begin at 0 and extend through the length of the array minus one.

. op1.op2 Is a reference to the op2 member of op1.

Declares or calls the method named op1 with the specified


() op1(params) parameters. The list of parameters can be an empty list. The list
is comma-separated.

Casts (converts) op1 to type. An exception will be thrown if the


(type) (type) op1
type of op1 is incompatible with type.

Creates a new object or array. op1 is either a call to a


new new op1
constructor, or an array specification.

op1 instanceof
instanceof Returns true if op1 is an instance of op2
op2

Precedence of Java Operators

20
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator: For example, x =
7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it
first gets multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence
appear at the top of the table, those with the lowest appear at the bottom. Within an expression,
higher precedence operators will be evaluated first.

Control Statements:
Programming languages provide various control structures that allow for more complicated
execution paths.
Java programming language provides the following types of loop to handle looping
requirements. Click the following links to check their detail.

While Loop in Java


21
A while loop statement in Java programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax
while(Boolean_expression)
{
//Statements
}

Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non zero value.When executing, if the boolean_expression
result is true, then the actions inside the loop will be executed. This will continue as long as the
expression result is true. When the condition becomes false, program control passes to the line
immediately following the loop.
Example:
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 15 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
This will produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
for Loop in Java
A for loop is a repetition control structure that allows you to efficiently write a loop that

22
needs to be executed a specific number of times. A for loop is useful when you know how many
times a task is to be repeated.
Syntax
for(initialization; Boolean_expression; update)
{
//Statements
}
Here is the flow of control in a for loop:
The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables and this step ends with a semi colon (;).
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed.
If it is false, the body of the loop will not be executed and control jumps to the next
statement past the for loop.
After the body of the for loop gets executed, the control jumps back up to the update
statement. This statement allows you to update any loop control variables. This
statement can be left blank with a semicolon at the end.
The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.
Example :
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 15; x = x+1)
{ System.out.print("value of x : " + x );
System.out.print("\n");
}
}}
This will produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13

23
value of x : 14
Do While Loop in Java
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax
do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the
loop execute once before the Boolean is tested. If the Boolean expression is true, the control
jumps back up to do statement, and the statements in the loop execute again. This process
repeats until the Boolean expression is false.
Example :
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 15 );
}
}
This will produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14

24
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Java supports the
following control statements.

Break Statement in Java


The break statement in Java programming language has the following two usages:
• When the break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement.
Syntax
break;
Example
public class Test {
public static void main(String args[])
{ int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 )
{ break; }
System.out.print( x );
System.out.print("\n");
}
}
}
This will produce the following result:
10
20
Continue Statement in Java

25
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
• In a for loop, the continue keyword causes control to immediately jump to the update
statement.
• In a while loop or do/while loop, control immediately jumps to the Boolean expression.
Syntax
continue;
Example
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 )
{ continue; }
System.out.print( x+ “ “ );
}
}
}
This will produce the following result:
10 20 40 50

Decision Making
Java programming language provides following types of decision making statements.

26
If Statement
An if statement consists of a Boolean expression followed by one or more statements.
Syntax
if (Boolean_expression)
{ //Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not, the first set of code after the end of the if statement (after the closing curly
brace) will be executed.
Example
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ) { System.out.print("This is if statement"); }
}
}

Output :
This is if statement.
If-else Statement
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
Syntax
if (Boolean_expression)
{ //Executes when the Boolean expression is true }
else
{ //Executes when the Boolean expression is false }
If the boolean expression evaluates to true, then the if block of code will be executed,
27
otherwise else block of code will be executed.
Example
public class Test {
public static void main(String args[]){
int x = 30;
if( x < 20 ) { System.out.print("This is if statement"); }
else
{ System.out.print("This is else statement"); }
}
}
Output :
This is else statement
The if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.
When using if, else if, else statements there are a few points to keep in mind.
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
if (Boolean_expression 1)
{ //Executes when the Boolean expression 1 is true }
else if (Boolean_expression 2)
{ //Executes when the Boolean expression 2 is true }
else if (Boolean_expression 3)
{ //Executes when the Boolean expression 3 is true }
else
{ //Executes when the none of the above condition is true }
Example
public class Test {
public static void main(String args[]){
int x = 30;

28
if( x == 10 ) { System.out.print("Value of X is 10"); }
else if( x == 20 ) { System.out.print("Value of X is 20"); }
else if( x == 30 ) { System.out.print("Value of X is 30"); }
else { System.out.print("This is else statement"); }
}
}
Output :
Value of X is 30
Switch Statement
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.
Syntax
switch(expression)
{
case value : //Statements break;
//optional
case value : //Statements break;
//optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The following rules apply to a switch statement:
• 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.
• 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.
Example
public class Test {

29
public static void main(String args[]){
//char grade = args[0].charAt(0);
char grade = 'C';
switch(grade)
{
case 'A' : System.out.println("Excellent!"); break;
case 'B' :
case 'C' : System.out.println("Well done"); break;
case 'D' : System.out.println("You passed");
case 'F' : System.out.println("Better try again"); break;
default : System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Output:
Well done
Your grade is C

The ? : Operator:
Conditional operator ? : can be used to replace if...else statements. It has the following general
form:
Exp1 ? Exp2 : Exp3 ;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
To determine the value of the whole expression, initially exp1 is evaluated.
• If the value of exp1 is true, then the value of Exp2 will be the value of the whole
expression.
• If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of
the entire expression.
ARRAYS
An array is simply a sequence of either objects or primitives all the same type and
packaged together under one identifier name.

30
An array is a structure that holds multiple values of the same type. The length of an array is
established when the array is created (at runtime). After creation, an array is a fixed-length
structure.
An array element is one of the values within an array and is accessed by its position within
the array.
Arrays are useful for grouping related information.
Declaring a Variable to Refer to an Array
To create an array, we have to first create an array variable of desired type.
General Syntax of Array Declaration
type var-name[];
or
type[] var-name;
Where, type declares the base type of the array.
Example
int[] anArray; // declare an array of integers
An array declaration has two components:
Array's type
Array's name.
Creating an Array
Arrays are created explicitly using Java's new operator.
The next step is allocating an array with enough memory for ten integer elements
and assigns the array to the variable anArray declared earlier.
anArray = new int[10]; // create an array of integers
when creating an array, we use the new operator, plus the data type of the array
elements, plus the number of elements desired enclosed within square brackets ('['
and ']').
Syntax
new elementType[arraySize]
EXAMPLE PROGRAM
public class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declare an array of integers

31
anArray = new int[10]; // create an array of integers
// assign a value to each array element and print
for (int i = 0; i < anArray.length; i++) {
anArray[i] = i;
System.out.print(anArray[i] + " ");
}
System.out.println();
}
}

Getting the Size of an Array


To get the size of an array,
arrayname.length
Here length is not a method. Length is a property provided by the Java platform for all arrays.
The for loop in our sample program iterates over each element of an Array, assigning values to
its elements. The for loop uses an Array. Length to determine when to terminate the loop.
Creating Format Strings
We have printf() and format() methods to print output with formatted numbers. TheString class
has an equivalent class method, format(), that returns a String object rather than a PrintStream
object.
Using String's static format() method allows you to create a formatted string that you can
reuse, as opposed to a one-time print statement. For example, instead of:
System.out.printf ("The value of the float variable is " + "%f, while the value of the
integer " + "variable is %d, and the string " + "is %s", floatVar, intVar, stringVar);
We can write:
String fs;
fs = String.format("The value of the float variable is " + "%f, while the value of the
integer " + "variable is %d, and the string " + "is %s", floatVar, intVar, stringVar);
System.out.println(fs);

32
Objects and classes in Java-class fundamentals-declaring objects-defining classes-
access specifiers – constructors- methods-inheritance-Method overriding-abstract
classes-using final with inheritance.
Class and objects:
A class is nothing but a blueprint or a template for creating different objects which
defines its properties and behaviors. Java class objects exhibit the properties and behaviors
defined by its class. A class can contain fields and methods to describe the behavior of an
object.

A class in Java can contain:

o fields
o methods
o constructors
o blocks
o nested class and interface

Syntax to declare a class:

Accesss specifier class <class_name>


{
field;
method;
}
Eg:
public class Cube
{
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
}
Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker,
pen, table, car etc. It can be physical or logical (tengible and intengible). The example of
integible object is banking system.

An object has three characteristics:

o state: represents data (value) of an object.

33
o behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
o identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But,it is used internally by the JVM to identify each
object uniquely.

For Example:

Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used
to write, so writing is its behavior.

Object Definitions:

Object is a real world entity.


Object is a run time entity.
Object is an entity which has state and behavior.
Object is an instance of a class.

Object creation using new keyword:

The new keyword is used to allocate memory at run time. It creates a Java object and
allocates memory for it on the heap. new is also used for array creation, as arrays are also
objects.

<class name> <object name>=new <class name()>;

Eg:

Rectangle rect = new Rectangle(10, 10);

It creates an object of the Rectangle class. This statement has three parts:

1. Declaration:

Declarations notify the compiler that name to refer to a variable whose type
is type. Declarations do not create new objects.

type name;

where type is the data type of the object and name is the name to be used for
the object.

Eg:

Rectangle rect;

34
2. Instantiation: The new keyword is a Java operator that creates the object.

Eg:

new Rectangle();

3. Initialization: The new operator is followed by a call to a constructor,

which initializes the new object.

Eg:

new Rectangle(10, 10);

Example: To find Area of Rectangle


class Rectangle
{
double length;
double breadth;
}
// This class declares an object of type Rectangle.
class RectangleDemo
{
public static void main(String args[])
{
Rectangle myrect = new Rectangle();
double area;
// assign values to myrect's instance variables
myrect.length = 10;
myrect.breadth = 20;
// Compute Area of Rectangle
area = myrect.length * myrect.breadth ;
System.out.println("Area is " + area);
}
}
Access Modifiers in java
The access modifiers in java specify accessibility (scope) of a data member, method,
constructor or class.
35
There are 4 types of java access modifiers:

1. Private (Visible to the class only )


2. default (Visible to the package )
3. protected (Visible to the package and all subclasses )
4. public (Visible to the world )

Private Access Modifier (most restrictive)


Methods, variables, and constructors that are declared private can only be accessed
within the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot
be private.

Private constructors can’t be instantiated from outside the class.

Example:

class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Public Access Modifier (least restrictive)

A class, method, constructor, interface, etc. declared public can be accessed from any
other class. Therefore, fields, methods, blocks declared inside a public class can be accessed
from any class belonging to the Java Universe.

36
However, to access public class in a different package, then the public class still needs
to be imported. Because of class inheritance, all public methods and variables of a class are
inherited by its subclasses.

Example:

//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Default Access Modifier

Any modifier is not specified, and then it is treated as default by default. The default
modifier is accessible only within package.

A variable or method declared without any access control modifier is available to


any other class in the same package. The fields in an interface are implicitly public static final
and the methods in an interface are by default public.

Example:
//save by A.java

37
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

Protected Access Modifier

The protected access modifier is accessible within package and outside the
package but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class and interface.
Example:

//save by A.java
package pack;
public class A
{
protected void msg()
{

38
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Java Access Modifiers Table for Class and Interface:

Visibility Public Access Modifier Default Access


Modifier

Within Same Package Yes Yes

From Outside the Same Yes No


Package

Access Modifiers for Methods and Variables:

Visibility Public Private Protected Default


Access Access Access Access
Modifier Modifier Modifier Modifier

39
Within Same Class Yes Yes Yes Yes

From Any Class in Yes No Yes Yes


Same Package

From Any Sub Class in Yes No Yes Yes


Same Package

From Any Sub Class Yes No Yes(Only By No


from Different Package Inheritance)

From Any Non Sub Yes No No No


Class in Different
Package

Methods in Java
Method describe behavior of an object. A method is a collection of statements that are
group together to perform an operation.
Syntax :
Modifier return-type methodName(parameter-list)
{
//body of method
}
Modifier : Modifier are access type of method.
Return Type : A method may return value. Data type of value return
by a method is declare in method heading.
Method name : Actual name of the method.
Parameter : Value passed to a method.
Method body : collection of statement that defines what method does.
40
Eg:
public double circleArea(double r)
{
double area;
area=3.14*r*r;
return area;
}
Example:To Find Minimum among two values
public class Minimum
{
int mini(int n1, int n2)
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
public static void main(String[] args)
{
int a = 11;
int b = 6;
Minimum o=new Minimum();
int c = o.mini(a, b);
System.out.println("Minimum Value = " + c);
}
}
Parameters Passing:
There are two ways to pass an argument to a method
Call by value

41
Call by reference
Call by Value:
In this approach copy of an argument value is pass to a method. The changes being
done in the called method, is not affected in the calling method.
Example:
public class Test
{ public void callByValue(int x)
{
x=100;
}
public static void main(String[] args)
{
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(“x=”+x);
}
}
Output: x=50
Call-by-Reference :
In this reference of an argument is pass to a method. Any changes made inside the
method will affect the agrument value.
Example:
public class Test
{
int x=10;
int y=20;
public void callByReference(Test t)
{
t.x=100;
t.y=50;
}
public static void main(String[] args)

42
{
Test ts = new Test();
System.out.println("Before "+ts.x+" "+ts.y);
ts.callByReference(ts);
System.out.println("After "+ts.x+" "+ts.y);
}
}
Output:
Before 10 20
After 100 50
Method Overloading in Java
If a class has multiple methods by same name but different parameters, it is known
as Method Overloading. Method overloading is also known as Static Polymorphism.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

Example of Method Overloading by changing the no. of arguments:

In this example, class calculation has two overloaded methods, first sum method
performs addition of two numbers and second sum method performs addition of three numbers.

class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

}
}
Example of Method Overloading by changing data type of argument:
43
In this example, class calculation2 have two overloaded methods that differs in
data type. The first sum method receives two integer arguments and second sum method
receives two double arguments.
class Calculation2
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);

}
}

main() method overloading:


A class can have any number of main methods by overloading.
class Overloading1
{
public static void main(int a)
{
System.out.println(a);
}
public static void main(String args[])
{
System.out.println("main() method invoked");
main(10);
}
}

Method Overloading and Type Promotion:


One data type is promoted to another type implicitly if no matching data type is found.
The possible promotion is given below:

44
Example of Method Overloading with TypePromotion:

class OverloadingCalculation1
{
void sum(int a,long b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);// second int literal will be promoted to long
obj.sum(20,20,20);

}
}

Constructors:

Constructor in java is a special type of method that is used to initialize the object.

45
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object. Constructor in Java cannot be abstract, static, final or
synchronized.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are three types of constructors:

1) Default constructor
2) No-argument constructor
3) Parameterized constructor

Default Constructor

If any constructor not defined in class, java generates one constructor at the time of
object creation by default. This constructor is known as default constructor.
Default constructor provides the default values to the object like 0, null etc. depending
on the type.

Syntax of default constructor:

<class_name>()
{
}

Example of default constructor

class Bike
{
Bike()
{
}
public static void main(String args[])
{
Bike b=new Bike();
}
}

No-argument constructor

46
Constructor with no arguments is known as no-argument constructor. The signature is
same as default constructor, however body can have any code unlike default constructor where
the body does nothing.
Example:
class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
}

Parameterized constructor

A constructor that has parameters is known as parameterized constructor.


Parameterized constructor is used to provide different values to the distinct objects.
Example:
class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}

Constructor overloading

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

Example of Constructor Overloading

47
class Student
{
int id;
String name;
int age;
Student(int i,String n)
{
id = i;
name = n;
}
Student(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}

public static void main(String args[])


{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}

Inheritance:

Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. Inheritance represents the IS-A relationship, also known as parent-
child relationship.

Why use inheritance in java

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


For Code Reusability.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name

//methods and fields

48
}

Types of inheritance

Single Inheritance
Multiple Inheritance (Through Interface)
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance (Through Interface)

Single Inheritance

Single Inheritance is the simple inheritance of all, When a class extends another
class(Only one class) then it called as Single inheritance. The below diagram represents the
single inheritance in java where Class B extends only one class Class A. Here Class B will be
the Sub class and Class A will be one and only Super class.

Example

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispA() method of ClassA
b.dispA();
49
//call dispB() method of ClassB
b.dispB();
}
}

Multiple Inheritance in Java

Multiple Inheritance is nothing but one class extending more than one class. Multiple
Inheritance is basically not supported by many Object Oriented Programming languages
such as Java, Small Talk, C# etc..(C++ Supports Multiple Inheritance). As the Child class has
to manage the dependency of more than one parent class. But using interfaces multiple
inheritance is achieved in Java.

Multilevel Inheritance

In Multilevel Inheritance a derived class will be inheriting a parent class and as well
as the derived class act as the parent class to other class. As seen in the below
diagram. ClassB inherits the property of ClassA and again ClassB act as a parent
for ClassC. In Short ClassA parent for ClassB and ClassB parent for ClassC.

50
MultiLevel Inheritance Example

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispA() method of ClassA
c.dispA();
//call dispB() method of ClassB
c.dispB();
//call dispC() method of ClassC
c.dispC();
}
}

Hierarchical Inheritance

In Hierarchical inheritance one parent class will be inherited by many sub classes. As
per the below example ClassA will be inherited by ClassB, ClassC and ClassD. ClassA will be
acting as a parent class for ClassB, ClassC and ClassD.

51
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
52
b.dispA();
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispC() method of ClassC
c.dispC();
//call dispA() method of ClassA
c.dispA();
//Assigning ClassD object to ClassD reference
ClassD d = new ClassD();
//call dispD() method of ClassD
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}

Hybrid Inheritance in Java

Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again
Hybrid inheritance is also not directly supported in Java only through interface only it is
achieved. Flow diagram of the Hybrid inheritance will look like below. ClassA will be acting as
the Parent class for ClassB & ClassC and ClassB & ClassC will be acting as Parent for ClassD.

Super Keyword:

The super keyword in java is a reference variable which is used to refer immediate
parent class object.

Whenever creating the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
53
It is used inside a sub-class method definition to call a method defined in the super
class. Private methods of the super-class cannot be called. Only public and protected
methods can be called by the super keyword.

It is also used by class constructors to invoke constructors of its parent class.

Syntax:
super. variablename;
super . <method-name>();

Usage of java super Keyword

super can be used to refer immediate parent class instance variable.


super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.

Example: to invoke base class constructor


class Employee
{
Employee()
{
System.out.println("Employee class Constructor");
}
}
class HR extends Employee
{
HR()
{
super(); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.

Usage of Java Method Overriding


Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
Method overriding is used for runtime polymorphism
54
Rules for Java Method Overriding
method must have same name as in the parent class
method must have same parameter as in the parent class.
must be IS-A relationship (inheritance).

Example:
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}

public static void main(String args[])


{
Bike obj = new Bike();
obj.run();
}
}
Output:
Bike is running safely

It will invoke derived class run method only. Invoke run method of base class by using
reference type.

class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}

public static void main(String args[])

55
{
Vehicle obj = new Vehicle(); //Vehicle reference and Vehicle object
Vehicle obj1 = new Bike(); //Vehicle reference but Bike object

obj.run();
obj1.run();
}
}
Output:
Vehicle is running
Bike is running safely

Using the super Keyword


When invoking a super class version of an overridden method the super keyword is
used.

Example:
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
super.run(); // invokes the super class method
System.out.println("Bike is running safely");
}

public static void main(String args[])


{
Vehicle obj = new Bike(); //Vehicle reference but Bike object

obj.run();
}
}
Output:
Vehicle is running
Bike is running safely

Difference between method overloading and method overriding

Method Overloading Method Overriding

56
Method Overloading Method Overriding

Parameter must be different and Both name and parameter must be same.
name must be same.

Compile time polymorphism. Runtime polymorphism.

Increase readability of code. Increase reusability of code.

Access specifier can be changed. Access specifier most not be more restrictive than
original method (can be less restrictive).

Abstract class:

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Another way, it shows only important things to the user and hides the internal details.

Ways to achieve Abstaction

There are two ways to achieve abstraction in java

1. Abstract class
2. Interface

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended


and its method implemented. It cannot be instantiated. If a class contains any abstract method
then the class is declared as abstract class.

• Abstract classes may or may not contain abstract methods, i.e., methods without body (
public void get(); )

• But, if a class has at least one abstract method, then the class must be declared
abstract.

• If a class is declared abstract, it cannot be instantiated.


57
• To use an abstract class, it should be inherit it from another class, provide
implementations to the abstract methods in it.

Example abstract class

abstract class A{}


Abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
• abstract keyword is used to declare the method as abstract.

• place the abstract keyword before the method name in the method declaration.

• An abstract method contains a method signature, but no method body.

• Instead of curly braces, an abstract method will have a semoi colon (;) at the end.

Example abstract method

abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method


abstract class Bike
{
abstract void run();
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
}
}

final keyword:

The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:

1. variable
2. method
3. class
58
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.

Java final variable

If variable is final, then the value of final variable cannot be changed (It will be
constant).

Example of final variable

There is a final variable speedlimit, while trying to change the value of this variable, it
can't be changed because final variable once assigned a value can never be changed.

class Bike
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400; //compile time error ;
}
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}
Java final method

If any method is declared as final, then it cannot be overridden.

Example of final method


class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run() // compile time error ; try to override final method run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
59
}
}

Java final class


If any class is declared as final, then cannot extend it.
Example of final class
final class Bike
{}
class Honda extends Bike // compile time error ; try to extend final class Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}

60

Вам также может понравиться