0% found this document useful (0 votes)
18 views170 pages

Unit 1 - AJP

Uploaded by

fortiratra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views170 pages

Unit 1 - AJP

Uploaded by

fortiratra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 170

Unit 1

Object Oriented Programming using Java

Prepared By:
Dr. Dheresh Soni
Syllabus of Unit 1
• Overview of the Java • Arrays
platform • Packages
• Introduction to Java: Java • Inheritance
Architecture • Exception Handling and
• Advantages of Java
Threading: Try, Catch,
• PATH and CLASSPATH
Finally, Throws
variables
• Creating Multithreaded
• Compiling and Running Java
Programs Programs,
• Class and Object: Creating • Thread Life Cycle
Classes, Interfaces, Creating • Input/Output Serialization and
Objects Object Serialization.
• Access Modifiers
Object Oriented Programming
 The major motivating factor - remove some of the flaws
encountered in the procedural approach.
 OOP treats data as a critical element - does not allow it
to flow freely, Ties data more closely to the functions
 OOP allows decomposition of a problem - number of
entities called objects and then builds data and
functions.
Object Oriented Programming
 Object-oriented programming is not the right of any
particular language.
 The languages should support several of the OOP
concepts to claim that they are object oriented.
 Object-based programming languages
– Data encapsulation
– Data hiding and access mechanisms
– Automatic initialization and clear-up Of Objects
– Operator overloading
 Object-oriented programming languages
– Object-based features + inheritance + dynamic
binding
 Basic concepts OOP - These include:
1. Objects 2. Classes 3. Data abstraction
4. Data encapsulation 5. Inheritance 6. Polymorphism
7. Dynamic binding 8. Message passing
Object Oriented Programming
Procedure oriented Object oriented
programming (POP) programming (OOP)

• Emphasis is on doing • Emphasis is on data rather


things (algorithms). than procedure.
• Large programs are • Programs are divided into
divided into smaller what are known as objects.
programs known as • Data structures are
functions. designed such that they
• Most of the functions characterize the objects.
share global data. • Data is hidden and cannot
• Data move openly around be accessed by external
the system from function functions.
to function. • Functions that operate on
• Functions transform data the data of an object are
from one form to another. tied together in the data
• Employs top-down structure.
approach in program
design.
Object Oriented Programming
Procedure oriented Object oriented
programming (POP) programming (OOP)

• Objects are not available • Objects may communicate


for communication with with each other through
each other. functions.
• New data and functions • New data and functions
can be easily added on can be easily added
top of program before whenever necessary.
using it.

 Basic concepts
OOP

1. Objects
2. Classes
3. Data abstraction
4. Data encapsulation
Object Oriented Programming
5. Inheritance
Object Oriented Programming
6. Polymorphism
I. Static Binding
II. Dynamic Binding

7. Dynamic binding

8. Message passing

employee . salary (name);


Object Message Information
Introduction to Java, Java platform & Java
Architecture
 Java is related to C++.
 Much of the character of Java is inherited from these
two languages.
 From C, Java derives its syntax.
 Object-oriented features were influenced by C++.
 Java was developed by James Gosling, Patrick
Naughton, Chris Warth, Ed Frank, and Mike Sheridan
at Sun Microsystems, Inc. in 1991.
 This language was initially called “Oak” but was
renamed “Java” in 1995.
 Why JAVA
 Problem - The trouble with C and C++ (and most other
languages) is that they are designed to be compiled for
a specific target.
 Solution – An easier and more cost-efficient—solution
was needed.
Introduction to Java, Java platform & Java
Architecture
 Platform-independent language that could be used to
produce code that would run on a variety of CPUs
under differing environments.

 3 important Component in JAVA - JDK, JRE & JVM

 JVM - JVM (Java Virtual Machine)


 Abstract machine.
 Called a virtual machine because it doesn't physically
exist.
 Specification that provides a runtime environment -
Java bytecode execution.
 It can also run those programs which are written in
other languages and compiled to Java bytecode.
 There are three notions of the JVM: specification,
implementation, and instance.
Introduction to Java, Java platform & Java
Architecture

JDK
Introduction to Java, Java platform & Java
Architecture
 JVM 4 main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment

 JVM Architecture
1. Classloader - Subsystem used to load class files. Three
built-in classloaders in Java.
 Bootstrap ClassLoader,
 Extension ClassLoader,
 System/Application ClassLoader.
2. Class Area – Stores per-class structures - runtime
constant pool, field and method data, the code for
methods.
3. Heap - Runtime data area in which objects are allocated.
Introduction to Java, Java platform & Java
Architecture
Introduction to Java, Java platform & Java
Architecture
4. Stack - Stores frames to holds local variables and partial
results.
5. Program Counter Register – Hold Address of the Java
virtual machine instruction currently being executed.
6. Native Method Stack - Hold all the native methods
7. Execution Engine -
 A virtual processor

 Interpreter - Read bytecode stream

 Just-In-Time (JIT) compiler - It is used to improve

the performance. JIT compiles parts of the byte code.


8. Java Native Interface - Java Native Interface (JNI) is a
framework which provides an interface to communicate
with another application written in another language like
C, C++ and Assembly etc.

 JRE - Java Runtime Environment.


 Written as Java RTE.
Introduction to Java, Java platform & Java
Architecture
Introduction to Java, Java platform & Java
Architecture
 A set of software tools which are used for developing
Java applications.
 Provide the runtime environment - It is the
implementation of JVM.
 It physically exists and contains a set of libraries +
other files.
 Implementation of JVM - Sun Micro Systems.

 JDK - Java Development Kit.


 A software development environment which is used
to develop Java applications and applets.
 It physically exists.
 It contains JRE + development tools.
 JDK is an implementation - Oracle Corporation:
 Standard Edition Java Platform
Introduction to Java, Java platform & Java
Architecture
Introduction to Java, Java platform & Java
Architecture
 Enterprise Edition Java Platform
 Micro Edition Java Platform

 The JDK contains a


 private Java Virtual Machine
 an interpreter/loader (java),
 a compiler (javac),
 an archiver (jar),
 a documentation generator (Javadoc), etc. to
complete the development of a Java Application.
Advantages of Java
1. Simple
2. Object-Oriented
3. Robust
4. Reliability
5. Multithreaded
6. Architecture-Neutral
7. Interpreted and High Performance
8. Distributed
9. Dynamic
PATH and CLASSPATH variables
 CLASSPATH
 CLASSPATH is an environment variable
 Used by Application ClassLoader to locate and load
the .class files.
 The CLASSPATH defines the path, to find third-party
and user-defined classes
 Include all the directories which contain .class files
and JAR files.
 You need to set the CLASSPATH if:
 You need to load a class that is not present in the
current directory or any sub-directories.
 You need to load a class that is not in a location
specified by the extensions mechanism.
 The CLASSPATH has a directory name or file name at
the end, So following points should be considered
PATH and CLASSPATH variables
 If a JAR or zip, the file contains class files, - end with
the name of the zip or JAR file.
 If class files placed in an unnamed package, - ends
with the directory that contains the class files.
 If class files placed in a named package - ends with
the directory that contains the root package.
 The default value of CLASSPATH is a dot (.) - means the
only current directory searched. Set the CLASSPATH
variable or using the - classpath command (for short -
cp).
 You can set multiple classpaths, then you need to
separate each CLASSPATH by a semicolon (;).
 There are two ways to set CLASSPATH:
 Command Prompt
 Setting Environment Variable.
PATH and CLASSPATH variables
 Method 1
 Step 1: Click on the Windows button and choose
Control Panel. Select System.
 Step 2: Click on Advanced System Settings.
 Step 3: A dialog box will open. Click on Environment
Variables.
 Step 4: If the CLASSPATH already exists in System
Variables, click on the Edit button then put a
semicolon (;) at the end. Paste the Path of MySQL-
Connector Java.jar file.

 If the CLASSPATH doesn't exist in System Variables,


then click on the New button and type Variable name
as CLASSPATH and Variable value as C:\Program
Files\Java\jre1.8\MySQL-ConnectorJava.jar;.;
Remember: Put ;.; at the end of the CLASSPATH.
PATH and CLASSPATH variables
 Method 2
 Type the following command in your Command Prompt
and press enter.
set CLASSPATH=%CLASSPATH%;
C:\Program Files\Java\jre1.8\rt.jar;
 Or open notepad write this code and save as .bat file
(example j.bat), save this file in place where cmd
prompt is showing
E:
cd JAVACODE
Set path="C:\Program Files\Java\jdk1.7.0_03\bin";.;
Set classpath= %classpath%;.;

 CLASSPATH is a variable name enclosed in sign (%) &


separated by semicolon, and after the (;) there is the
PATH of rt.jar file.
PATH and CLASSPATH variables
 PATH:
 PATH is an environment variable
 Used to find and locate binary files like “java” and
“javac” and to locate needed executables from the
command line or Terminal window.
 Include or mention JDK_HOME/bin directory in a PATH
environment variable.
 The PATH can not be overridden by providing command
and PATH is only used by the operation system(OS) to
find binary files.
 Syntax
 set PATH=%PATH%; // To set PATH in the window OS.
 C:\Program Files\Java\JDK1.5.10\bin
// To set PATH in Unix OS
 export PATH=${PATH}:/opt/Java/JDK1.5.10/bin
PATH and CLASSPATH variables
You can run java by IDE or CMD prompt. To run in CMD
prompt set path of java using following steps
1. Open C drive program file java folder jdk folder
bin folder and copy path given at top in url.
2. From the desktop, right click the Computer icon.
3. Choose Properties from the context menu.
4. Click the Advanced system settings link.
5. Click Environment Variables. In the section System
Variables & User variables, find the PATH environment
variable and select it. Click Edit. If the PATH environment
variable does not exist, click on New.
6. Click on the Edit button of System Variable & User
variable; specify the value of the PATH environment
variable. Click OK. Close all remaining windows by
clicking OK.
7. Reopen Command prompt window, and run your java
code.
PATH and CLASSPATH variables
Difference between PATH and CLASSPATH
PATH CLASSPATH

PATH is an environment CLASSPATH is also an


variable. environment variable.
It is used by the operating It is used by Application
system to find the ClassLoader to locate the .class
executable files (.exe). file.
You are required to include You are required to include all the
the directory which directories which contain .class
contains .exe files. and JAR files.
PATH environment variable The CLASSPATH environment
once set, cannot be variable can be overridden by
overridden. using the command line option -
cp or -CLASSPATH to both javac
and java command.
Compiling and Running Java Programs
 Simple Program
/* This is a simple Java program. Call this file
"example.java" */
class example
{ //Program begins with call to main()
public static void main(String args[ ])
{ System.out.println("This is a simple Java program."); }
}
 Saving the Program –
 Name your source file is very important. example.java.
 Source file use the .java filename extension.
 Source file is officially called a compilation unit.

 Compiling the Program –


 Execute the compiler, javac specifying the name of the

source file with file extension


 C:\>javac example.java
Compiling and Running Java Programs
 Executing the program –
 The javac compiler creates a file called example.class
that contains the bytecode version of the program.
 The Java bytecode is the intermediate representation of
your program.
 To actually run the program, you must use the Java
interpreter, called java.
 C:\>java example
 Output - This is a simple Java program.
 Class name same as file name why? –
 When Java source code is compiled, each individual
class is put into its own output file named after the
class and using the .class extension. This is why it is
a good idea to give your Java source files the same
name as the class they contain—the name of the
source file will match the name of the .class file.
Compiling and Running Java Programs
 When you execute the Java interpreter as just
shown, you are actually specifying the name of the
class that you want the interpreter to execute. It will
automatically search for a file by that name that has
the .class extension. If it finds the file, it will execute
the code contained in the specified class.
Class and Object: Creating Classes, Interfaces &
Objects
 Class Fundamentals –
 The most important thing to understand - defines a
new data type.
 Once defined, new - can be used to create objects of
that type.
 Class is a template for an object, and an object is an
instance of a class.
 Because an object is an instance of a class, you will
often see the two words object and instance used
interchangeably.

 The General Form of a Class –


 Declare its exact form and nature.
 Specifying the data that it contains and the code that
operates on that data.
 A class is declared by use of the class keyword.
Class and Object: Creating Classes, Interfaces,
Creating Objects
 Classes can get much more complex. The general form
of a class definition is shown here:

class classname
{
type instance-variable1; type instance-variable2;
type methodname1(parameter-list)
{ // body of method }
}

 The data, or variables - instance variables or data


member.
 The code is contained within methods or member
function
 Collectively, the methods and variables defined within
a class are called members of the class.
Class and Object: Creating Classes, Interfaces,
Creating Objects
 Variables
 Defined within a class are called instance variables
 Because each instance of the class contains its own
copy of these variables.
 Data for one object is separate and unique from the
data for another.
 All methods have the same general form as main( ),
most methods will not be specified as static or public.
 General form of a class does not specify a main( )
method. Java classes do not need to have a main( )
method. You only specify one if that class is the
starting point for your program.

 A Simple Class - class called Box, three instance


variables: width, height, and depth. it does not contain
any methods
Class and Object: Creating Classes, Interfaces,
Creating Objects
class Box
{
double width;
double height;
double depth;
}
 The new data type is called Box. You will use this
name to declare objects of type Box.
 It is important to remember that a class declaration
only creates a template; it does not create an actual
object.
 To actually create a Box object, you will use a
statement like the following:

Box mybox = new Box(); // create a Box object


called mybox
Class and Object: Creating Classes, Interfaces,
Creating Objects
 After this statement executes, mybox will be an
instance of Box.
 Every Box object will contain its own copies of the
instance variables width, height, and depth.
 To access these variables, you will use the dot (.)
operator.
mybox.width = 100;
//A program that uses the Box class. Call this file
BoxDemo.java
class Box
{ double width; double height; double depth; }
// This class declares an object of type Box.
class BoxDemo
{
public static void main(String args[ ])
Class and Object: Creating Classes, Interfaces,
Creating Objects
{
Box mybox = new Box( );
double vol;
mybox.width = 10; // assign values to mybox's instance
variables mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
// compute volume of box
System.out.println("Volume is " + vol);
}
}
 output: Volume is 3000.0
Class and Object: Creating Classes, Interfaces,
Creating Objects
 Declaring Objects –
 When you create a class, you are creating a new data
type.
 To declare objects of a class is a two-step process.
 First, you must declare a variable of the class
type. This variable does not define an object. It is a
variable that can refer to an object.
 Second, an actual, physical copy of the object and
assign it to that variable by using the new operator.
The new operator dynamically allocates memory for
an object and returns a reference to it.
 All class objects must be dynamically allocated. To
declare an object of type Box:
Box mybox = new Box();
 Any attempt to use mybox at this point will result in a
compile-time error. In reality, mybox simply holds the
memory address of the actual Box object.
Class and Object: Creating Classes, Interfaces,
Creating Objects

 Methods –
 Classes usually consist of two things: instance
variables and methods.
 Java gives them so much power and flexibility. This
is the general form of a method:
Class and Object: Creating Classes, Interfaces,
Creating Objects
 Syntax:
type name(parameter-list)
{ // body of method }

 Adding a Method –
 A class that contains only data, it rarely happens. You
will use methods to access the instance variables
 Methods define the interface to most classes
 Allows the class implementer to hide the specific
layout of internal data structures behind cleaner
method abstractions.
// This program includes a method inside the box class.
class Box
{
double width; double height; double depth;
void volume( ) // display volume of a box
{
Class and Object: Creating Classes, Interfaces,
Creating Objects
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[ ])
{
Box mybox1 = new Box(); Box mybox2 = new Box();
mybox1.width = 10; // assign values to mybox1's
instance variables mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3; // assign different values to
mybox2's instance variables mybox2.height = 6;
mybox2.depth = 9;
mybox1.volume( ); // display volume of first box
mybox2.volume( ); // display volume of second box
Class and Object: Creating Classes, Interfaces,
Creating Objects
}
}
This program generates the following output.
Volume is 3000.0
Volume is 162.0

Look closely at the following two lines of code:


mybox1.volume();
mybox2.volume();
Returning a Value - A better way to implement volume( ) is
to have it compute the volume of the box and return the
result to the caller.
// Now, volume( ) returns the volume of a box. class Box
{
double width; double height; double depth;
double volume( ) // compute and return volume
Class and Object: Creating Classes, Interfaces,
Creating Objects
{
return width * height * depth;
}
}
class BoxDemo4
{
public static void main(String args[])
{
Box mybox1 = new Box(); Box mybox2 = new Box(); double
vol;
mybox1.width = 10; // assign values to mybox1's instance
var. mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3; //assign different values to mybox2's
instance variables mybox2.height = 6;
mybox2.depth = 9;
Class and Object: Creating Classes, Interfaces,
Creating Objects
vol = mybox1.volume(); //get volume of first box
System.out.println("Volume is " + vol);
vol = mybox2.volume(); //get volume of second box
System.out.println("Volume is " + vol);
}
}
• Adding a Method That Takes Parameters –
While some methods don’t need parameters. Parameters
allow a method to be generalized. That is, a parameterized
method can operate on a variety of data and/or be used
in a number of slightly different situations.
int square( )
{ return 10 * 10; }
While this method does, indeed, return the value of 10
squared.
Class and Object: Creating Classes, Interfaces,
Creating Objects
• You modify the method so that it takes a parameter, as
shown, then you can make square( ) much more useful.
int square(int i)
{ return i * i; }

Now, square( ) will return the square of whatever value it is


called with.
int x, y;
x = square(5); // x equals 25 y = 2;
x = square(y); // x equals 4
It is important to keep the two terms parameter and
argument straight.

In the preceding examples, the dimensions of each box


had to be set separately by use of a sequence of
statements, such as:
Class and Object: Creating Classes, Interfaces,
Creating Objects
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
While this code works, it is troubling for two reasons.
First, it is clumsy and error prone.
Second, instance variables should be accessed only
through methods defined by their class. In the future, you
can change the behaviour of a method, but you can’t change
the behaviour of an exposed instance variable.

Thus, a better approach to setting the dimensions of a box


is to create a method that takes the dimension of a box in
its parameters and sets each instance variable
appropriately.

// This program uses a parameterized method.


Class and Object: Creating Classes, Interfaces,
Creating Objects
class Box
{
double width; double height; double depth;
double volume() // compute and return volume
{
return width * height * depth;
}
void setDim(double w, double h, double d) // sets
dimensions of box
{
width = w; height = h; depth = d;
}
}
class BoxDemo5
{
public static void main(String args[])
{
Class and Object: Creating Classes, Interfaces,
Creating Objects
Box mybox1 = new Box(); Box mybox2 = new Box();
double vol;
mybox1.setDim(10, 20, 15); // initialize each box
mybox2.setDim(3, 6, 9);
vol = mybox1.volume(); // get volume of first box
System.out.println("Volume is " + vol);
vol = mybox2.volume(); // get volume of second box
System.out.println("Volume is " + vol);
}
}
Interfaces –
• Abstract a class’s interface from its implementation
• You can specify what a class must do, but not how it
does it.
• Interfaces are syntactically similar to classes
• Differ from class –
Class and Object: Creating Classes, Interfaces,
Creating Objects
– They lack instance variables, and
– Their methods are declared without any body.

 Once it is defined, any number of classes can implement


an interface. Also, one class can implement any
number of interfaces.
 The interface keyword, Java allows “one interface,
multiple methods” aspect of polymorphism. To
implement an interface, a class must create the complete
set of methods defined by the interface.
 Interfaces are designed to support dynamic method
resolution at run time.
 Problem in class - In order for a method to be called from
one class to another, both classes need to be present at
compile time so the Java compiler can check to ensure
that the method signatures are compatible.
Class and Object: Creating Classes, Interfaces,
Creating Objects
 This requirement by itself makes for a static and non-
extensible class environment. Inevitably in a system like
this, functionality gets pushed up higher and higher in
the class hierarchy so that the mechanisms will be
available to more and more subclasses.
 Interfaces are designed to avoid this problem. Interfaces
are in a different hierarchy from classes, it is possible for
classes that are unrelated in terms of the class hierarchy
to implement the same interface. This is where the real
power of interfaces is realized. Syntax of Interface
access mode interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
final- data type varname1 = value;
final- data type varname2 = value;
}
Class and Object: Creating Classes, Interfaces,
Creating Objects
 Here, access is either public or not used.
 When no access specifier is included, then default access
results, and the interface is only available to other
members of the package in which it is declared.
 When it is declared as public, the interface can be used
by any other code.
 name is the name of the interface, and can be any valid
identifier.
 Methods which are declared have no bodies - abstract
methods;
 Each class that includes an interface must implement
all of the methods.
 Variables can be declared inside of interface and they
are implicitly final and static. Means they cannot be
changed by the implementing class and they must also be
initialized with a constant value.
Class and Object: Creating Classes, Interfaces,
Creating Objects
 All methods and variables are implicitly public if the
interface.
Example
Callback
{ void callback(int param); }
Implementing Interfaces –
 Once an interface has been defined, one or more classes
can implement that interface.
 To implement an interface - add implements clause in a
class definition, and then create the methods defined by
the interface.
Syntax:
Access mode class classname [extends superclass]
[implements interface [,interface...]]
{ // body of interface }
Class and Object: Creating Classes, Interfaces,
Creating Objects
 If a class implements more than one interface, the
interfaces are separated with a comma.
 If a class implements two interfaces that declare the same
method, then
1. Same method will be used by clients of either
interface.
2. Methods must be declared public.
3. Type signature of the implementing method must
match exactly

Example
class Client implements Callback
{ // Implement Callback's interface
public void callback(int param)
{System.out.println("callback called with " + param);}
}
Class and Object: Creating Classes, Interfaces,
Creating Objects
 It is both permissible and common for classes - define
additional members of their own.
Example
class Client implements Callback
{
public void callback(int param) // Implement
Callback's interface
{
System.out.println("callback called with " + param);
}
void nonIfaceMeth()
{
System.out.println("Classes that implement
interfaces " + "may also define other
members, too.");
}
}
Class and Object: Creating Classes, Interfaces,
Creating Objects
Accessing Implementations Through Interface
References –

 Declare variables as object references that use an


interface rather than a class type.
 Any instance of class that implements the declared
interface can be referred to by such a variable.
 When you call a method through one of these
references, the correct version will be called based on
the actual instance of the interface being referred to.
 This is one of the key features of interfaces. The method
to be executed is looked up dynamically at run time,
allowing classes to be created later than the code which
calls methods on them.
 The calling code can dispatch through an interface
without having to know anything about the “callee.”
Class and Object: Creating Classes, Interfaces,
Creating Objects
class TestIface
{
public static void main(String args[])
{
Callback c = new Client();
c.callback(42);
}
}

The output of this program is shown here:


callback called with 42

 Variable c is declared to be of the interface type


Callback.
 c can be used to access the callback( ) method, it cannot
access any other members of the Client class.
Class and Object: Creating Classes, Interfaces,
Creating Objects
 Example to demonstrate the polymorphic power of
such a reference.
class AnotherClient implements Callback
{ // Another implementation of Callback.
public void callback(int param)
// Implement Callback's interface
{
System.out.println("Another version of callback");
System.out.println("param squared is " + (param*param));
}
}
class: class TestIface2
{
public static void main(String args[])
{
Callback c = new Client();
Class and Object: Creating Classes, Interfaces,
Creating Objects
AnotherClient ob = new AnotherClient();
c.callback(42);
c = ob; // c now refers to AnotherClient
object c.callback(42);
}
}

The output from this program is shown here:


callback called with 42
Another version of callback
p squared is 1764

The version of callback( ) that is called is determined by


the type of object that c refers to at run time.
Class and Object: Creating Classes, Interfaces,
Creating Objects
Partial Implementations –
 If a class includes an interface but does not fully
implement all the methods defined by that interface,
then that class must be declared as abstract.
 By default interface is public static final so it does not
have constructor.

 For example:
abstract class Incomplete implements Callback
{
int a, b;
void show();
{ System.out.println(a + " " + b); }
}

 Any class that inherits Incomplete must implement


callback( ) or be declared abstract itself.
Class and Object: Creating Classes, Interfaces,
Creating Objects
Interfaces Can Be Extended (Extending Interface) –
 One interface can inherit another by use of the
keyword extends.
 The syntax is the same as for inheriting classes.
Example:
interface A // One interface can extend another.
{
void meth1();
void meth2();
}
interface B extends A //B now includes meth1() and meth2()
-- it adds meth3().
{ void meth3(); }
class MyClass implements B
{ //This class must implement all of A and B
public void meth1()
Class and Object: Creating Classes, Interfaces,
Creating Objects
{ System.out.println("Implement meth1()."); }
public void meth2()
{ System.out.println("Implement meth2()."); }
public void meth3()
{ System.out.println("Implement meth3()."); }
}
class IFExtend
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2(); • Try to remove the implementation for
ob.meth3(); meth1( ) in MyClass.
} Ans - Compile-time error
} • Implement all methods defined by
that interface, including any that are
inherited from other interfaces.
Class and Object: Creating Classes,
Interfaces, Creating Objects
Differences between classes and interfaces and
extending interfaces
Key Class Interface
Supported A class can have Interface can have
1 Methods both an abstract as only abstract
well as concrete methods. Java 8
methods. onwards, it can have
default as well as
static methods.
2 Multiple Multiple Inheritance Interface supports
Inheritanc is not supported. Multiple Inheritance.
e
3 Supported final, non-final, Only static and final
Variables static and non-static, variables are
variables supported. permitted.
Class and Object: Creating Classes,
Interfaces, Creating Objects
Differences between classes and interfaces and
extending interfaces
Key Class Interface
4 Implem A class can Interface cannot
entation implement an implement an interface, it
interface. can extend an interface.
5 Keywor A class is Interface is
d declared using declared using
class keyword. interface keyword.
6 Inherita A class can inherit Interface caninherit
nce another class using only an interface.
extends keyword
and implement an
interface.
Class and Object: Creating Classes,
Interfaces, Creating Objects
Differences between classes and interfaces and
extending interfaces
Key Class Interface
7 Inheritan A class can be Interface can only be
ce inherited using implemented using
extends keyword. implements keyword.
8 Access A class can have Interface can only have
any type of members public members.
like private, public.
9 Construc A class can have Interface cannot have a
tor constructor constructor.
methods.
Access Modifiers
 Java provides many levels of protection
 control over the visibility of variables and methods
within classes, subclasses, and packages.
 Classes and packages are both means of encapsulating
and containing the name space and scope of variables
and methods.
 Packages act as containers for classes and other
subordinate packages.
 The class is Java’s smallest unit of abstraction.
Because of the interplay between classes and packages.
 Four categories of visibility for class members:

A. Subclasses in the same package


B. Non-subclasses in the same package
C. Subclasses in different packages
D. Classes that are neither in the same package nor
subclasses
Access Modifiers
Access Modifiers
The three access specifiers, private, public, and protected
 Anything declared public can be accessed from
anywhere.
 Anything declared private cannot be seen outside of its
class.
 When a member does not have an explicit access
specification, it is visible to subclasses as well as to
other classes in the same package. This is the default
access.
 If you want to allow an element to be seen outside your
current package, but only to classes that subclass your
class directly, then declare that element protected.
 A class has only two possible access levels:
default and public.
Example –
 Two packages and five classes. Two different packages
need to be stored in directories named p1 and p2.
Access Modifiers
 The source for the first package p1 defines three
classes: Protection, Derived, and SamePackage.
 In 2nd package p2 - The two classes defined Protection2
and OtherPackage.

This is file Protection.java:


package p1;
public class Protection
{
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
Access Modifiers
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
This is file Derived.java:
package p1;
class Derived extends Protection
{
Derived()
{
System.out.println("derived constructor");
System.out.println("n = " + n); // class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
Access Modifiers
This is file SamePackage.java:
package p1;
class SamePackage
{
SamePackage()
{
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);// class only
// System.out.println("n_pri = " + p.n_pri);
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
This is file Protection2.java:
package p2;
class Protection2 extends p1.Protection
{
Access Modifiers
Protection2()
{
System.out.println("derived other package constructor");
// class or package only
// System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
This is file OtherPackage.java:
package p2;
class OtherPackage
{
OtherPackage()
{
p1.Protection p = new p1.Protection();
Access Modifiers
System.out.println("other package constructor");
// class or package only
// System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
// class, subclass or package only
// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}

 If you wish to try these two packages, here are two


test files you can use. The test file for p1 is shown next:

package p1; // Demo package p1.


public class Demo // Instantiate the various classes in p1
{
public static void main(String args[])
{
Access Modifiers
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}

 The test file for p2 is shown next:


package p2; // Demo package p2.
public class Demo1 // Instantiate the various classes
in p2.
{
public static void main(String args[])
{
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}
Arrays
Arrays
 An array is a group of like-typed variables that are
referred to by a common name.
 Arrays of any type can be created and may have one or
more dimensions.
 A specific element in an array is accessed by its index.
 All arrays in JAVA are dynamically allocated.
 Obtaining an array is a two-step process.
 First, you must declare a variable of the desired array
type.
 Second, you must allocate the memory that will hold
the array, using new, and assign it to the array
variable.
One-Dimensional Arrays –
 A one-dimensional array is, essentially, a list of like- typed
variables.
 To create an array, you first must create an array variable
of the desired type.
Arrays
Step 1: Syntax - type var-name[ ];
Example - int month_days[ ];
Step 2: Syntax - array-var = new type[size];
Example - month_days = new int[12];
Example:
class Array
{
public static void main(String args[])
{
int month_days[ ];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
Arrays
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + "
days.");
}
}

Multidimensional Arrays –
 In Java, multidimensional arrays are actually arrays of
arrays.
 To declare a multidimensional array variable, specify
each additional index using another set of square
brackets.
Example - int twoD[ ][ ] = new int[4][5];
Arrays
class TwoDArray
{
public static void main(String args[])
{
int twoD[ ][ ];
twoD[ ][ ]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++) for(j=0; j<5; j++)
{
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
Arrays
Arrays
}
}

Output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19

 When you allocate memory for a multidimensional array,


you need only specify the memory for the first
(leftmost) dimension.
int twoD[ ][ ] = new int[4][ ];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
Arrays
 While there is no advantage to individually allocating
the second dimension arrays in this situation, there
may be in others.
Example - Sizes of the second dimension are unequal.
// Manually allocate differing size second dimensions.
class TwoDAgain
{
public static void main(String args[])
{
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
{
Arrays
for(j=0; j<i+1; j++)
{
twoD[i][j] = k; k++;
}
for(i=0; i<4; i++)
{
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
} Output:
0
12
345
6789
Arrays
 The use of uneven (or, irregular) multidimensional
arrays is not recommended for most applications,
because it runs contrary to what people expect to find
when a multidimensional array is encountered. It can be
used effectively in some situations.
 It is possible to initialize multidimensional arrays. To do
so, simply enclose each dimension’s initializer within its
own set of curly braces.
 Example - The following program creates a 3 by 4 by 5,
three-dimensional array. It then loads each element with
the product of its indexes.
// Demonstrate a three-dimensional array.
class threeDMatrix
{
public static void main(String args[])
{
int threeD[][][] = new int[3][4][5];
Arrays
i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}
Arrays
This program generates the following output:
00000 00000 00000
00000 01234 02468
00000 02468 0 4 8 12 16
00000 0 3 6 9 12 0 6 12 18 24
Alternative Array Declaration Syntax –
 There is a second form that may be used to declare an
array:
Syntax: type[ ] var-name;
Example: int al[ ] = new int[3]; or int[ ] a1 = new int[3];
The following declarations are also equivalent:
char twod1[ ][ ] = new char[3][4];
char[ ][ ] twod1 = new char[3][4];
 Useful when specifying an array as a return type for a
method.
Packages
 The name of each class example was taken from the
same name space. This means that a unique name had
to be used for each class to avoid name collisions.
 Java provides a mechanism for partitioning the class
name space into more manageable chunks. This
mechanism is the package.
 The package is both a naming and a visibility control
mechanism.
 Define classes inside a package that are not accessible
by code outside that package.
 You can also define class members that are only exposed
to other members of the same package.
 This allows your classes to have intimate knowledge of
each other, but not expose that knowledge to the rest of
the world.
Defining a Package –
 Include a package command as the first statement.
Packages
 Any classes declared within that file will belong to the
specified package.
 The package statement defines a name space in which
classes are stored.
 If you omit the package statement, the class names are
put into the default package, which has no name.
Default package is fine for short, sample programs.
Syntax: package pkg;
Example: package MyPackage;
 creates a package called MyPackage.
 Java uses file system directories to store packages.
Directory name must match the package name exactly.
 More than one file can include the same package
statement. You can create a hierarchy of packages.
Syntax: package pkg1[.pkg2[.pkg3]];
Example: package java.awt.image;
Packages
 A package needs to be stored in UNIX - java/awt/image,
WINDOWS - java\awt\image, or MACH - java:awt:image
 Cannot rename a package without renaming the
directory in which the classes are stored.

Finding Packages and CLASSPATH


 Packages are mirrored by directories.
 Important question: How does the Java run-time
system know where to look for packages that you
create?
 Answer - First, by default, the Java run-time system
uses the current working directory as its starting point.
Thus, if your package is in the current directory, or a
subdirectory of the current directory, it will be found.
 Second, you can specify a directory path or paths by
setting the CLASSPATH environmental variable.
package MyPack;
Packages
package MyPack;
class Balance
{
String name; double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal>0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
Packages
public static void main(String args[])
{
Balance current[ ] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++)
current[i].show();
}
}
Using the following command line:
javac AccountBalance.java
java MyPack.AccountBalance

Importing Packages –
 Packages are a good mechanism for compartmentalizing
diverse classes from each other, it is easy to see why all
of the built- in Java classes are stored in packages.
Packages
 There is no core Java classes in the unnamed default
package; all of the standard classes are stored in some
named package.
 It could become tedious to type in the long dot-separated
package path name for every class you want to use.
 For this reason, Java includes the import statement to
bring certain classes, or entire packages, into visibility.
 If you are going to refer to a few dozen classes in your
application, however, the import statement will save a lot
of typing.
 import statements occur immediately following the
package statement (if it exists) and before any class
definitions.
 This is the general form of the import statement:
Syntax: import pkg1[.pkg2].(classname|*);
Example: import java.util.Date;
import java.io.*;
Packages
All of the standard Java classes included with Java are
stored in a package called java.
The basic language functions are stored in a package
inside of the java package called java.lang.
To import every package or class that you want to use
import java.lang.*;
Inheritance
 Inheritance is one of the cornerstones of object-oriented
programming because it allows the creation of
hierarchical classifications.
 Using inheritance, you can create a general class that
defines behaviour common to a set of related items.
 A class that is inherited is called a superclass. The class
that does the inheriting is called a subclass.
 Subclass is a specialized version of a superclass. It
inherits all of the instance variables and a method
defined by the superclass and adds its own elements.
 To inherit a class, you simply incorporate the definition of
one class into another by using the extends keyword.

Example – The following program creates a superclass


called A and a subclass called B. Keyword extends is used
to create a subclass of A.
Inheritance
The general form of a class declaration that inherits a
superclass is shown here:
Syntax: class subclass-name extends superclass-name
{ // body of class }
class A // Simple inheritance - Create a superclass.
{
int i, j;
void showij( )
{ System.out.println("i and j: " + i + " " + j); }
}
class B extends A //Create a subclass by extending class A.
{
int k;
void showk( )
{ System.out.println("k: " + k); }
Inheritance
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();
superOb.i = 10; // The superclass may be used by itself.
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
Inheritance
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();
}
}

Output :
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
Inheritance
 You can only specify one superclass for any subclass that
you create. Java does not support the inheritance of
multiple superclasses into a single subclass.
 You can, create a hierarchy of inheritance in which a
subclass becomes a superclass of another subclass. No
class can be a superclass of itself.
Member Access and Inheritance –
 Although a subclass includes all of the members of its
superclass
 It cannot access those members of the superclass that have
been declared as private.
For example - This program contains an error and will not
compile.
class A // Create a superclass.
{
int i; // public by default
Inheritance
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}
class B extends A // A's j is not accessible here.
{
int total; void sum()
{ total = i + j; } // ERROR, j is not accessible here
class Access
{
public static void main(String args[])
{
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
Inheritance
System.out.println("Total is " + subOb.total);
}
}

Using super –
 When you will want to create a superclass that keeps
the details of its implementation to itself
 In this case, there would be no way for a subclass to
directly access or initialize these variables on its own.
Since encapsulation is a primary attribute of OOP.
 Java provides a solution to this problem. Whenever a
subclass needs to refer to its immediate superclass, it can
do so by use of the keyword super.
 Super has two general forms.
1. calls the superclass constructor.
2. To access a member of the superclass that has been
hidden by a member of a subclass.
Inheritance
Using super to Call Superclass Constructors –
 A subclass can call a constructor method defined by its
superclass by use of the following
super(parameter-list);
 super( ) must always be the first statement executed inside
a subclass’ constructor. Example:
class Box // A complete implementation of BoxWeight
{
private double width;
private double height;
private double depth;
Box(Box ob) // construct clone of an object
{
width = ob.width; // pass object to constructor
height = ob.height;
depth = ob.depth;
}
Inheritance
Box(double w, double h, double d)
// constructor used when all dimensions specified
{ width = w; height = h; depth = d; }
double volume() // compute and return volume
{ return width * height * depth; }
}

class BoxWeight extends Box


// BoxWeight now fully implements all constructors.
{
double weight; // weight of box
BoxWeight(BoxWeight ob)
// construct clone of an object
{
super(ob); // pass object to constructor
weight = ob.weight;
}
Inheritance
BoxWeight(double w, double h, double d, double m)
// constructor when all parameters are specified
{
super(w, h, d); // call superclass constructor
weight = m;
}
}
class DemoSuper
{
public static void main(String args[])
{
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " +
mybox1.weight;
Inheritance
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " +
myclone.weight);
System.out.println(); Output:
} Volume of mybox1 is 3000.0
} Weight of mybox1 is 34.3
Volume of myclone is 3000.0
Weight of myclone is 34.3

Pay special attention to this constructor in BoxWeight( ):


BoxWeight(BoxWeight ob)// construct clone of an object
{
super(ob); // pass object to constructor
weight = ob.weight;
}
Inheritance
A Second Use for super –
 The second form of super acts like this pointer
 Except that it always refers to the superclass of the
subclass in which it is used.
 Synatx: super.member
 Member can be either a method or an instance variable.
 This second form of super is most applicable to situations
in which member names of a subclass hide members by
the same name in the superclass.
Example
class A // Using super to overcome name hiding.
{ int i; }

class B extends A // Create a subclass by extending class A.


{
int i; // this i hides the i in A
B(int a, int b)
Inheritance
{
super.i = a; // i in A
i = b; // i in B
}
void show()
{
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper
{
public static void main(String args[])
{
B subOb = new B(1, 2);
subOb.show();
}
}
Inheritance
Output:
i in superclass: 1
i in subclass: 2

Creating a Multilevel Hierarchy –


 Simple class hierarchies that consist of only a superclass
and a subclass.
 You can build hierarchies that contain as many layers of
inheritance as you like. It is perfectly acceptable to use a
subclass as a superclass of another.
Example -Three classes called A, B, and C,
C can be a subclass of B, which is a subclass of A.
class Box // Start with Base Class Box.
{
private double width;
private double height;
private double depth;
Inheritance
Box(Box ob) // construct clone of an object
{
width = ob.width; // pass object to constructor
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

double volume() // compute and return volume


{ return width * height * depth; }
}
Inheritance
class BoxWeight extends Box //Derived Class Add weight.
{
double weight; // weight of box
BoxWeight(BoxWeight ob) //construct clone of an object
{
super(ob); // pass object to constructor
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m)
{
super(w, h, d); // call superclass constructor weight =
m;
}
}
class Shipment extends BoxWeight
//Final Derived Class Add shipping costs
Inheritance
{
double cost;
Shipment(Shipment ob) // construct clone of an object
{
super(ob); // pass object to constructor
cost = ob.cost;
}
Shipment(double w, double h, double d, double m, double
c) // constructor when all parameters are specified
{
super(w, h, d, m); // call superclass constructor
cost = c;
}
}
class DemoShipment //calling classes
{
public static void main(String args[])
{
Inheritance
Shipment shipment1 = new Shipment(10, 20, 15, 10,
3.41);
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is "+
shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
}
}
Output:
Volume of shipment1 is 3000.0
Weight of shipment1 is 10.0
Shipping cost: $3.41
Inheritance
Method Overriding
 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.
class A // Method overriding.
{
int i, j;
A(int a, int b)
{ i = a;
j = b; }
void show() // display i and j
{ System.out.println("i and j: " + i + " " + j); }
Inheritance
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show() // display k – this overrides show() in A
{ System.out.println("k: " + k); }
//super.show() for class A
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
Inheritance
subOb.show(); // this calls show() in B
}
} Output: for Class A Show()
Output: i and j: 1 2
k: 3 k: 3

Dynamic Method Dispatch –

 Previous example Method overriding - they do not show


its power. Method overriding forms the basis for one of
Java’s most powerful concepts: dynamic method
dispatch.
 Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time,
rather than compile time.
 Dynamic method dispatch is important because this is
how Java implements run-time polymorphism.
Inheritance
 A superclass reference variable can refer to a subclass
object. Java uses this fact to resolve calls to overridden
methods at run time.
 When an overridden method is called through a
superclass reference, Java determines which version of
that method to execute based upon the type of the
object being referred to at the time the call occurs. Thus,
this determination is made at run time. Example

class A// Dynamic Method Dispatch


{
void callme()
{
System.out.println("Inside A's callme method");
}
}
Inheritance
class B extends A // override callme()
{
void callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{
void callme() // override callme()
{
System.out.println("Inside C's callme method");
}
}
Inheritance
class Dispatch
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
} Output:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
Inheritance
Why Overridden Methods? –
 Overridden methods allow Java to support run-time
polymorphism.
 Polymorphism is essential - It allows a general class to
specify methods that will be common to all of its
derivatives, while allowing subclasses to define the
specific implementation of some or all of those methods.
 Overridden methods are another way that Java
implements the “one interface, multiple methods”
aspect of polymorphism.
 Dynamic, run-time polymorphism is one of the most
powerful mechanisms that object- oriented design
brings to bear on code reuse and robustness.
 The superclass provides all elements that a subclass
can use directly. This allows the subclass the flexibility to
define its own methods
 Combining inheritance with overridden methods, a
superclass can define the general form of the methods
that will be used by all of its subclasses.
Inheritance
Applying Method Overriding –
class Figure // Using run-time polymorphism.
{
double dim1;
double dim2;
Figure(double a, double b)
{ dim1 = a;
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); }
double area() // override area for rectangle
Inheritance
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{ super(a, b); }
double area() // override area for right triangle
{
System.out.println("Inside Area for Triangle."); return
dim1 * dim2 / 2;
}
}
class FindAreas
{
public static void main(String args[])
Inheritance
{
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
Exception Handling and Threading: Try, Catch,
Finally, Throws
 A Java exception is an object that describes an
exceptional (that is, error) condition that has occurred in
a piece of code.
 When an exceptional condition arises, an object
representing that exception is created and thrown in the
method that caused the error.
 Method may choose to handle the exception itself or at
some point, the exception is caught and processed.
 Exceptions can be generated by
1. the Java run- time system
2. they can be manually generated by your code
3. thrown by Java relate to fundamental errors that
violate the rules of the Java language
4. the constraints of the Java execution environment.
 Manually generated exceptions are typically used to
report some error condition to the caller of a method.
Exception Handling and Threading: Try, Catch,
Finally, Throws
 Java exception handling is managed via five keywords:
1. Try
2. Catch
3. Throw
4. Throws, and
5. Finally.
 Program statements that you want to monitor for
exceptions are contained within a try block.
 If an exception occurs within the try block, it is thrown.
 Your code can catch this exception (using catch) and
handle it in some rational manner.
 System- generated exceptions are automatically
thrown by the Java run-time system.
 To manually throw an exception, use the keyword
throw.
 Any exception that is thrown out of a method must be
specified as such by a throws clause.
Exception Handling and Threading: Try, Catch,
Finally, Throws
 Any code that absolutely must be executed before a
method returns is put in a finally block.
 This is the general form of an exception-handling block:
Syntax
Try
{ // block of code to monitor for errors }
catch (ExceptionType1 exOb)
{ // exception handler for ExceptionType1 }
catch (ExceptionType2 exOb)
{ // exception handler for ExceptionType2 }
// ... finally
{ // block of code to be executed before try block
ends }
Exception Handling and Threading: Try, Catch,
Finally, Throws
Exception Types –

 All exception types are subclasses of the built-in class


Throwable - top of the exception class hierarchy.
 Immediately below = two subclasses that partition
exceptions into two distinct branches.

1. One branch is headed by Exception.


 For exceptional conditions that user programs
should catch.
 Subclass to create your own custom exception
types. There is an important subclass of
Exception, called RuntimeException.
 Exceptions of this type are automatically defined
for the programs
2. Other branch is topped by Error
Exception Handling and Threading: Try, Catch,
Finally, Throws
 Defines exceptions that are not expected to be
caught under normal circumstances by your
program.
 Exceptions of type Error are used by the Java run-
time system to indicate errors having to do with the
run-time environment, itself.

Uncaught Exceptions –
 What happens when you don’t handle them.
 Example - Divide-by-zero error.
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
} }
Exception Handling and Threading: Try, Catch,
Finally, Throws
 System detects the attempt to divide by zero, it
constructs a new exception object and then throws
this exception. The execution of Exc0 to stop, because
once an exception has been thrown, it must be caught by
an exception handler and dealt with immediately.
 We haven’t supplied any exception handlers of our own,
so the exception is caught by the default handler
provided by the Java run-time system. Any exception
that is not caught by your program will ultimately be
processed by the default handler.
 The default handler displays a string describing the
exception, Here is the output generated when this
example is executed.

java.lang.ArithmeticException: / by zero at
Exc0.main(Exc0.java:4)
Exception Handling and Threading: Try, Catch,
Finally, Throws
Try and catch block –
 Default exception handler provided by the Java run-
time system is useful for debugging - handle an
exception yourself.
 Doing so provides two benefits.
1. fix the error.
2. Prevents the program from automatically
terminating.
 To guard against and handle a run-time error, simply
enclose the code that you want to monitor inside a try
block.
 Immediately following the try block, include a catch
clause that specifies the exception type that you wish
to catch. Example - division-by-zero error:
class Exc2
{
public static void main(String args[])
Exception Handling and Threading: Try, Catch,
Finally, Throws
{
int d, a;
try // monitor a block of code.
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e) // catch divide-by-zero
error
{ System.out.println("Division by zero."); }
System.out.println("After catch statement.");
}
}
Output:
Division by zero.
After catch statement.
Exception Handling and Threading: Try, Catch,
Finally, Throws
Displaying a Description of an Exception –

 Throwable overrides the toString( ) method (defined by


Object) so that it returns a string containing a description
of the exception.
 Display this description in a println( ) statement by
simply passing the exception as an argument.
Example –
catch (ArithmeticException e)
{
System.out.println("Exception: " + e); a = 0;
// set a to zero and continue
}

Displays the following message:


Exception: java.lang.ArithmeticException: / by zero
Exception Handling and Threading: Try, Catch,
Finally, Throws
Multiple catch block –
 In some cases, more than one exception could be raised
by a single piece of code.
 To handle this type of situation, you can specify two or
more catch clauses, each catching a different type of
exception.
 When an exception is thrown, each catch statement is
inspected in order, and the first one whose type
matches that of the exception is executed.
 After one catch statement executes, the others are
bypassed, and execution continues after the try/catch
block.
Example traps two different exception types:
class MultiCatch //Demonstrate multiple catch statements.
{
public static void main(String args[])
Exception Handling and Threading: Try, Catch,
Finally, Throws
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[ ] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{ System.out.println("Divide by 0: " + e); }
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("Array index : " + e); }
System.out.println("After try/catch blocks.");
}
}
Exception Handling and Threading: Try, Catch,
Finally, Throws
Output:
C:\>java MultiCatch a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg a = 1
Array index : java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.
 When you use multiple catch statements - Remember that
exception subclasses must come before any of their
superclasses. – Reason??

Nested try Statements –


 try statement can be nested - try statement can be
inside the block of another try.
Exception Handling and Threading: Try, Catch,
Finally, Throws
Nested try Statements –

 try statement can be nested - try statement can be


inside the block of another try.
 Each time a try statement is entered, the context of that
exception is pushed on the stack. If an inner try
statement does not have a catch handler for a particular
exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match.
 This continues until one of the catch statements
succeeds, or until all of the nested try statements are
exhausted. If no catch statement matches, then the Java
run-time system will handle the exception.

Example that uses nested try statements:


class NestTry
{
Exception Handling and Threading: Try, Catch,
Finally, Throws
public static void main(String args[])
{
try
{
int a = args.length;
/* If no command-line args are present, the
following statement will generate a divide-by-zero
exception. */
int b = 42 / a;
System.out.println("a = " + a);
try // nested try block
{
/* If one command-line arg is used, then a
divide-by-zero exception will be generated by the
following code. */
if(a==1)
{a = a/(a-a);} // division by zero
Exception Handling and Threading: Try, Catch,
Finally, Throws
/* If two command-line args are used, then
generate an out-of-bounds exception. */
if(a==2)
{
int c[ ] = { 1 };
c[42] = 99; // generate an out-of-bounds
exception
}
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("Array index out-of-bounds: " +
e); }
}
catch(ArithmeticException e)
{ System.out.println("Divide by 0: " + e); }
}
}
Exception Handling and Threading: Try, Catch,
Finally, Throws
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException

Finally block –
 When exceptions are thrown, execution in a method
takes a rather abrupt, nonlinear path that alters the
normal flow through the method.
 Depending upon how the method is coded, it is even
possible for an exception to cause the method to return
prematurely. This could be a problem in some methods.
 So the finally keyword is designed to address this
contingency.
Exception Handling and Threading: Try, Catch,
Finally, Throws
 finally creates a block of code that will be executed
after a try/catch block has completed
 The finally block will execute whether or not an
exception is thrown.
 Any time a method is about to return to the caller from
inside a try/catch block, via an uncaught exception or an
explicit return statement, the finally clause is also
executed just before the method returns.
 Useful for closing file handles and freeing up any
other resources that might have been allocated at the
beginning of a method with the intent of disposing of
them before returning.
 The finally clause is optional. However, each try
statement requires at least one catch or a finally
clause.
Exception Handling and Threading: Try, Catch,
Finally, Throws
Example -
class FinallyDemo // Demonstrate finally.
{
static void procA() // Exception out of the method.
{
try
{
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally
{ System.out.println("procA's finally"); }
}
static void procB()// Return from within a try block.
{
try
{
Exception Handling and Threading: Try, Catch,
Finally, Throws
System.out.println("inside procB");
return;
}
finally
{ System.out.println("procB's finally"); }
}
static void procC()// Execute a try block normally.
{
try
{ System.out.println("inside procC"); }
finally
{ System.out.println("procC's finally"); }
}
public static void main(String args[])
{
try
{ procA(); }
Exception Handling and Threading: Try, Catch,
Finally, Throws
catch (Exception e) Output
{ System.out.println("Exception inside procA
caught"); } procA’s finally
procB(); Exception caught
procC(); inside procB
} procB’s finally
} inside procC
procC’s finally
Throw and throws keywords –
 Throw - Catching exceptions that are thrown by the Java
run-time system. However, it is possible for your program
to throw an exception explicitly, using the throw
statement. The general form of throw is shown here:
throw ThrowableInstance;
 ThrowableInstance must be an object of type Throwable
or a subclass of Throwable.
Exception Handling and Threading: Try, Catch,
Finally, Throws
There are two ways you can obtain a Throwable object:
1. using a parameter into a catch clause, or
2. creating one with the new operator.
 The flow of execution stops immediately after the throw
statement; any subsequent statements are not
executed.
 The nearest enclosing try block is inspected to see if it
has a catch statement that matches the type of the
exception.
1. If it does find a match, control is transferred to that
statement.
2. If not, then the next enclosing try statement is
inspected, and so on.
3. If no matching catch is found, then the default
exception handler halts the program and prints the
stack trace.
Exception Handling and Threading: Try, Catch,
Finally, Throws
Example -
class ThrowDemo // Demonstrate throw.
{
static void demoproc()
{
try
{ throw new NullPointerException("demo"); }
catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
try
{ demoproc(); }
catch(NullPointerException e)
Exception Handling and Threading: Try, Catch,
Finally, Throws
{ System.out.println("Recaught: " + e); }
}
}

Output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
The program also illustrates how to create one of Java’s
standard exception objects. Pay close attention to this
line:
throw new NullPointerException("demo");
All of Java’s built- in run-time exceptions have at least
two constructors:

1. one with no parameter and


2. one that takes a string parameter.
Exception Handling and Threading: Try, Catch,
Finally, Throws
Throws –
 If a method is capable of causing an exception that it
does not handle, it must specify this behaviour so that
callers of the method can guard themselves against that
exception.
 This can be done by including a throws clause in the
method’s declaration. A throws clause lists the types of
exceptions that a method might throw.
 This is necessary for all exceptions, except those of type
Error or RuntimeException, or any of their subclasses.
 All other exceptions that a method can throw must be
declared in the throws clause. If not, a compile-time
error will result.
Syntax
type method-name(parameter-list) throws exception-list
{ // body of method }
Exception Handling and Threading: Try, Catch,
Finally, Throws
Exception-list is a comma-separated list of the exceptions
that a method can throw.
Example - Incorrect program that tries to throw an
exception that it does not catch. Because the program
does not specify a throws clause to declare this fact, the
program will not compile.

class ThrowsDemo
// This program contains an error and will not compile.
{
static void throwOne()
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{ throwOne(); }
Exception Handling and Threading: Try, Catch,
Finally, Throws
}

Two changes.
First, you need to declare that throwOne( ) throws
IllegalAccessException.
Second, main( ) must define a try/catch statement that
catches this exception.

Corrected Example is shown here:


class ThrowsDemo // This is now correct.
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
Exception Handling and Threading: Try, Catch,
Finally, Throws
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}

Output:
inside throwOne
caught java.lang.IllegalAccessException: demo
Creating Multithreaded Programs
Multithreading: Fundamentals –

 Threads, are lightweight process.


 They share the same address space and cooperatively
share the same heavyweight process.
 Interthread communication is inexpensive, and context
switching from one thread to the next is low cost.
 Java provides built-in support for multithreaded
programming and make use of process-based
multitasking environments.
 A multithreaded program contains two or more parts
that can run concurrently.
 Each part of such a program is called a thread, and
each thread defines a separate path of execution.
 Multithreading is a specialized form of multitasking.
There are two distinct types of multitasking: process-
based and thread-based.
Creating Multithreaded Programs
 A process is, in essence, a program that is executing.
Thus, process-based multitasking is the feature that
allows your computer to run two or more programs
concurrently.
 Thread-based multitasking environment, the thread is
the smallest unit of dispatchable code. This means that
a single program can perform two or more tasks
simultaneously.
 Multitasking threads require less overhead than
multitasking processes. Processes are heavyweight
tasks that require their own separate address spaces.
 Interprocess communication is expensive and limited.
Context switching from one process to another is also
costly.
 Multithreading enables you to write very efficient
programs that make maximum use of the CPU, because
idle time can be kept to a minimum.
Creating Multithreaded Programs
 This is especially important for the interactive,
networked environment in which Java operates.

 Creating Multiple Threads –


Example - program creates three child threads:
class NewThread implements Runnable
// Create multiple threads.
{
String name;
Thread t; // name of thread
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
Creating Multithreaded Programs
public void run() // This is the entry point for thread.
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{ System.out.println(name + "Interrupted"); }

System.out.println(name + " exiting.");


}
}
class MultiThreadDemo
{
Creating Multithreaded Programs
public static void main(String args[])
{
new NewThread("One"); // start threads new
NewThread("Two");
new NewThread("Three");
try
{ Thread.sleep(10000); }
// wait for other threads to end
catch (InterruptedException e)
{ System.out.println("Main thread Interrupted"); }

System.out.println("Main thread exiting.");


}
}

Output
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
Creating Multithreaded Programs
New thread: Thread[Three,5,main] One: 2
One: 5 Three: 2
Two: 5 Two: 2
Three: 5 One: 1
One: 4 Three: 1
Two: 4 Two: 1
Three: 4 One exiting.
One: 3 Two exiting.
Three: 3 Three exiting.
Two: 3 Main thread exiting
Thread Life Cycle
In Java, a thread always exists in any one of the following
states.
1. New –
 A new thread is created,
 Code has not been run yet
2. Active-
 When a thread invokes the start() method,
 Active state contains two states within it: one
is runnable, and the other is running.
3. Runnable-
 A thread may be running or may be ready to run at any
given instant of time.
 It is the duty of the thread scheduler
 A program implementing multithreading acquires a fixed
slice of time to each individual thread.
Thread Life Cycle
 Each and every thread runs for a short span of time
and when that allocated time slice is over.
 All those threads that are willing to run, waiting for their
turn to run, lie in the runnable state.
 In the runnable state, there is a queue where the
threads lie.
4. Running:-
 When the thread gets the CPU, it moves from the
runnable to the running state.
 Generally, the most common change in the state of a
thread is from runnable to running and again back to
runnable.
5. Blocked or Waiting-
 Thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the
waiting state.
Thread Life Cycle
6. Timed Waiting –
 To avoid starvation, a timed waiting state is given to
thread for a specific span of time, and not forever.
 The sleep() method puts the thread in the timed wait
state. After the time runs out, the thread wakes up and
start its execution from when it has left earlier.
7. Terminated –
 A thread reaches the termination state because of the
following reasons:
1. Normal termination: When a thread has finished its
job, then it exists or terminates normally.
2. Abnormal termination: It occurs when some
unusual events such as an unhandled exception or
segmentation fault.
 A terminated thread means the thread is no more in the
system. In other words, the thread is dead, and there is
no way one can respawn (active after kill) the dead
thread.
Thread Life Cycle
Thread Life Cycle
Implementation of Thread States –
 Get the current state of a thread using
the Thread.getState() method.
 The java.lang.Thread.State class of Java provides the
constants ENUM to represent the state of a thread.
 These constants are:
1. public static final Thread.State NEW - It represents
the first state of a thread that is the NEW state.
2. public static final Thread.State RUNNABLE - It
represents the runnable state.It means a thread is
waiting in the queue to run.
3. public static final Thread.State BLOCKED - It
represents the blocked state. In this state, the thread
is waiting to acquire a lock.
4. public static final Thread.State WAITING - It
represents the waiting state. A thread will go to this
state when it invokes the Object.wait() method, or
Thread Life Cycle
Thread.join() method with no timeout. A thread in
the waiting state is waiting for another thread to
complete its task.
5. public static final Thread.State TIMED_WAITING -
It represents the timed waiting state. Difference -
Waiting has no time constraint, whereas timed
waiting has the time constraint. A thread invoking
the following method reaches the timed waiting
state.
1. sleep
2. join with timeout
3. wait with timeout
4. parkUntil
5. parkNanos
6. public static final Thread.State TERMINATED - It
represents the final state of a thread that is
terminated or dead. A terminated thread means it
has completed its execution.
Input/Output & Object Serialization
 How data is sent over the network or how to save files on a
disk. This is possible with mechanism
called Serialization and Deserialization.

Serialization
 It is the process of converting the state of an object into
a byte stream.
 A byte-stream is a Java I/O (Input/Output) stream
which is essentially flows of data that a programmer can
either read from or write.
 Byte Streams read or write one byte of data at a time.
Now we have converted the object into a byte-stream
which can be saved onto a disk, communicated over the
network, etc.
 It is mainly used in Hibernate, RMI, JPA, EJB and JMS
technologies.
Input/Output & Object Serialization
Input/Output & Object Serialization
Deserialization
 The reverse operation of serialization is
called deserialization
 Byte-stream is converted into an object.
 To use them again, we need to convert these byte-
streams back to their respective Objects. This reverse
process of converting object into byte-stream is
called Deserialization.
 The serialization and deserialization process is platform-
independent, it means you can serialize an object on
one platform and deserialize it on a different platform.
 Example - The image is a simple illustration of the
Serialization-Deserialization process in Java.
Why Do We Need Serialization in Java-
Serialization mechanism is usually used when there is a need
to send your data (objects) over the network or to store in
files.
Input/Output & Object Serialization
 Hardware components like network infrastructure, hard
disk etc understands only bytes and bits, not the java
objects.
 Serialization is used in this case which translates Java
object's state to byte-stream to send it over the network
or save it in file.

How Do We Serialize An Object –


 Serialization in java can be implemented
using java.io.Serializable interface.
 java.io.Serializable interface is a marker interface. To make
a Java object serializable we implement
the java.io.Serializable interface.
 writeObject() method of ObjectOutputStream class is used
for serializing an Object. It is used to "mark" Java classes so
that the objects of these classes may get a certain capability.
 The Cloneable and Remote are also marker interfaces.
Input/Output & Object Serialization
 The Serializable interface must be implemented by the class
whose object needs to be persisted.
 The String class and all the wrapper classes implement
the java.io.Serializable interface by default.

 The ObjectOutputStream class is used to write primitive


data types, and Java objects to an OutputStream.
 Only objects that support the java.io.Serializable interface
can be written to streams.
 An ObjectInputStream deserializes objects and primitive
data written using an ObjectOutputStream.

Example: Creating a Student class - serializing the object of


the Student class.
Input/Output & Object Serialization
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Student implements java.io.Serializable


{
public String stu_Name;
public String stu_Addr;
public int stu_Id;

public static void main(String[] args)


{
Student std = new Student();
std.stu_Name = "George";
std.stu_Addr = "ABC,XYZ";
std.stu_Id = 1;
try
Input/Output & Object Serialization
{
FileOutputStream fileOut = new
FileOutputStream("storeObject.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
//Serializing object
out.writeObject(std);
out.close(); // Close the output stream.
fileOut.close(); // Close the file.
System.out.printf("Object serialized");
}
catch (IOException i)
{
i.printStackTrace();
}
}
}
Input/Output & Object Serialization
Example: Code for deserializing the same object
import java.io.*;
public class Student implements java.io.Serializable
{
public String stu_Name;
public String stu_Addr;
public int stu_Id;

public static void main(String[] args)


{
Student std = new Student(); // Create a Student object.
std.stu_Name = "George";
std.stu_Addr = "ABC,XYZ";
std.stu_Id = 1;

Student deserializedStudent;
// To hold the deserialized byte-stream
Input/Output & Object Serialization
try
{
// Serializing the student object – std
FileOutputStream fileOut = new
FileOutputStream("storeObject.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(std);
out.close();
fileOut.close(); // Serialization complete
System.out.printf("Object serialized");
// Deserialization process
FileInputStream fileIn = new
FileInputStream("storeObject.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
deserializedStudent = (Student) in.readObject();
//Deserialization
in.close();
fileIn.close();
Input/Output & Object Serialization
// Printing the deserialized object.
System.out.println("Deserialized Student...");
System.out.println("Name: " + deserializedStudent.stu_Name);
System.out.println("Address: " +deserializedStudent.stu_Addr);
}
catch (IOException i)
{ i.printStackTrace(); }

catch (Exception e)
{
System.out.println("Class not found");
e.printStackTrace();
return; Output:
} Deserialized Student...
} Name: George
} Address: ABC,XYZ
Input/Output & Object Serialization
Input/Output & Object Serialization
 While Serialization the writeObject() method is used.
Whereas, in Deserialization the readObject() method is
used.
 An object to be made serializable it is absolutely
mandatory for the object’s class to implement the
Serializable interface.
 An interface is like a class but with some differences, It is
used to show only the important things to the user and
hide internal working details away from the user.
 The Serializable interface tells the JVM (Java Virtual
Machine) that the objects of this class are ready for
serialization and/or deserialization.
 Machines do not understand the human language - Source
code. To bridge the gap we need to translate the source
code. This is where the JVM comes in.
Input/Output & Object Serialization
Java Serialization with Inheritance (IS-A Relationship)
Java Serialization with Aggregation (HAS-A Relationship)
Java Serialization with the static data member
Java Serialization with array or collection
Externalizable in java:

 The Externalizable interface provides the facility of writing


the state of an object into a byte stream in compress
format.
 It is not a marker interface.
 The Externalizable interface provides two methods:

1. public void writeExternal(ObjectOutput out) throws


IOException
2. public void readExternal(ObjectInput in) throws
IOException
Input/Output & Object Serialization
Java Transient Keyword
 If you don't want to serialize any data member of a class,
you can mark it as transient.

SerialVersionUID:

 The serialization process at runtime associates an id with


each Serializable class which is known as SerialVersionUID.
 It is used to verify the sender and receiver of the serialized
object. It can be Public and private as well
 The sender and receiver must be the same. To verify it,
SerialVersionUID is used.
 InvalidClassException will be thrown when you deserialize
the object.
 Declare our own SerialVersionUID in the Serializable class,
you need to create a field SerialVersionUID and assign a
value to it.
 It must be of the long type with static and final.

You might also like