Inheritance.ppt inheritance topic related to java

vadlaprasanna796 18 views 96 slides Aug 31, 2025
Slide 1
Slide 1 of 96
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96

About This Presentation

Inheritance.ppt inheritance topic related to java


Slide Content

UNIT-II 1
Java Programming
Unit-II

UNIT-II 2

UNIT-II 3
Contents
Inheritance:
Definition, types of Inheritance
Member Access rules
Superclass and subclass
super keyword
final keyword
Base class Object
Polymorphism:
Method overriding
Dynamic Method Dispatch
Abstract classes and methods
Interfaces:
Definition, Interfaces vs abstract classes
Implementing interfaces
Accessing through interfaces
Extending interfaces

UNIT-II 4

UNIT-II 5
► Inheritance is the process by which one object acquires the properties of
another object.
Definition:
► The class that is inherited is called a superclass or baseclass.
► The class that does the inheriting is called a subclass or derivedclass.
► Subclass is a specialized version of a superclass.

UNIT-II 6
Types of Inheritance:

UNIT-II 7
The general form of a class definition that inherits a superclass uses the
keyword extends and is shown as:
class subclass-name extends superclass-
name
{
//body of class
}
Syntax:

UNIT-II 8
Sample program: Single Inheritance
class A
{
int i,j;
void show( )
{
System.out.println(“i=”+i+” j=“+j);
}
}
class B extends A
{
int p,q;
void display( )
{
System.out.println(“p=“+p+” q=“+q);
}
void all( )
{
System.out.println(“i=”+i+” j=“+j+
“ p=“+p+” q=“+q);
}
}
class InheritanceDemo1
{
public static void main(String args[ ])
{
A obj1=new A( );
B obj2=new B( );
obj1.i=10;
obj1.j=20;
obj2.i=30;
obj2.j=40;
obj2.p=50;
obj2.q=60;
obj1.show( );
obj2.display( );
obj2.all( );
obj2.show( );
}
}
O/P:
i=10 j=20
p=50 q=60
i=30 j=40 p=50 q=60
i=30 j=40

UNIT-II 9
Java supports the following access specifiers(Modifiers)
public
private
protected
No modifier(default)

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.
Member Access:

UNIT-II 10
Sample program: Use of private keyword
class A
{
private int i,j;
void show( )
{
System.out.println(“i=”+i+” j=“+j);
}
}
class B extends A
{
int p,q;
void display( )
{
System.out.println(“p=“+p+” q=“+q);
}
void all( )
{
System.out.println(“i=”+i+” j=“+j+
“ p=“+p+” q=“+q);
}
}
class InheritanceDemo2
{
public static void main(String args[ ])
{
A obj1=new A( );
B obj2=new B( );
obj1.i=10;
obj1.j=20;
obj2.i=30;
obj2.j=40;
obj2.p=50;
obj2.q=60;
obj1.show( );
obj2.display( );
obj2.all( );
obj2.show( );
}
}
Compile time ERROR

UNIT-II 11
Superclass variable referencing a subclass object:
► A reference variable of a superclass can be assigned a reference to
any subclass derived from that superclass.

UNIT-II 12
Sample program: Superclass variable referencing a subclass object
class A
{
int i,j;
void show( )
{
System.out.println(“i=”+i+” j=“+j);
}
}
class B extends A
{
int p,q;
void display( )
{
System.out.println(“p=“+p+” q=“+q);
}
void all( )
{
System.out.println(“i=”+i+” j=“+j+
“ p=“+p+” q=“+q);
}
}
class InheritanceDemo3
{
public static void main(String args[ ])
{
A obj1=new A( );
B obj2=new B( );
obj1.i=10;
obj1.j=20;
obj2.i=30;
obj2.j=40;
obj2.p=50;
obj2.q=60;
obj1.show( );
obj1=obj2;
obj1.show( );
}
}
O/P:
i=10 j=20
i=30 j=40

UNIT-II 13
super keyword:
super has two general forms:
1) To call the superclass constructor.
2) To access a member of the superclass.
Whenever a subclass needs to refer to its immediate superclass,

it can do so by use of the keyword super.

UNIT-II 14
super to call the superclass constructor:
► A subclass can call a constructor defined by its superclass by use of

the following form of super:
super(parameter-list)
Note: super( ) must always be the first statement inside a subclass constructor.

UNIT-II 15
class A{
int i, j;
A( ){
System.out.println(“A default”);
}
A(int a, int b){
i=a;
j=b;
System.out.println(“A with 2 args”);
}
void show( ){
System.out.println(“i=”+i+” j=“+j);
}}
class B extends A{
int p,q;
B( ){
System.out.println(“B default”);
}
B(int a, int b, int c, int d){
super(a,b);
p=c;
q=d;
Sample program: super(parameter-list)
System.out.println(“B with 4 args”);
}
void all( ){
System.out.println(“i=”+i+” j=“+j+“ p=“+p+”


q=“+q);
}}
class SuperConstructor{
public static void main(String args[ ]){
A obj1=new A( );
B obj2=new B(30,40,50,60);
obj1.show( );
obj2.all( );
obj2.show( );
}}
O/P:
A default
A with 2 args
B with 4 args
i=0 j=0
i=30 j=40 p=50 q=60
i=30 j=40

UNIT-II 16
► 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.
Second use of super keyword;
The general form is:
super.member
► The super always refers to the superclass of the subclass in which it is used.

UNIT-II 17
class A{
int i, j;
A( ){
System.out.println(“A default”);
}
A(int a, int b){
i=a;
j=b;
System.out.println(“A with 2 args”);
}
void show( ){
System.out.println(“i=”+i+” j=“+j);
}}
class B extends A{
int i, j, p, q;
B( ){
System.out.println(“B default”);
}
B(int a, int b, int c, int d){
super(a,b);
i=c;
j=d;
Sample program: super.member
System.out.println(“B with 4 args”);
}
void all( ){
System.out.println(“Ai=”+super.i+”Aj=“+
super.j+“ i=“+i+” j=“+j);
}}
class SuperMember{
public static void main(String args[ ]){
A obj1=new A( );
B obj2=new B(30,40,50,60);
obj1.show( );
obj2.all( );
obj2.show( );
}}
O/P:
A default
A with 2 args
B with 4 args
i=0 j=0
Ai=30 Aj=40 i=50 j=60
i=30 j=40

UNIT-II 18
Multilevel Inheritance:
subclass of A
superclass of C
superclass of B
subclass of B

UNIT-II 19
class A
{
int i,j;
A( )
{
System.out.println("A default");
}
}
class B extends A
{
int p,q;
B( )
{
System.out.println("B default");
}
}
Sample Program: Multilevel Inheritance
O/P: ?
class C extends B
{
int x,y;
C( )
{
System.out.println("C default");
}
}
class ConstructorOrder1
{
public static void main(String args[ ])
{
C c1=new C();
}
}

UNIT-II 20
► If super( ) is not used, then the default or parameter less constructor of each


superclass will be executed.
In what order Constructors are called:
► In a class hierarchy, constructors are called in the order of derivation,
from superclass to subclass.
► Since super( ) must be the first statement executed in a subclass constructor,
this order is the same whether or not super( ) is used.

UNIT-II 21
class C extends B {
int x,y;
C( ) {
System.out.println("C default");
}
C(int a,int b,int c,int d,int e,int f) {
super(a,b,c,d);
x=e;
y=f;
System.out.println("C 6 args");
}
void display( )
{ System.out.println("i="+i+"j="+j+"p="+p+"q="
+ q+"x="+x+"y="+y);
}}
class ConstructorOrder2 {
public static void main(String args[]) {
C c1=new C(10,20,30,40,50,60);
c1.display();
}}
class A{
int i,j;
A( ) {
System.out.println("A default");
}
A(int a, int b) {
i=a;
j=b;
System.out.println("A 2 args");
}}
class B extends A {
int p,q;
B( ) {
System.out.println("B default");
}
B(int a,int b,int c,int d) {
super(a,b);
p=c;
q=d;
System.out.println("B 4 args");
}}
Sample Program: Multilevel Inheritance

UNIT-II 22
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 overriden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass.
► The version of the method defined by the superclass will be hidden.
► The superclass version of an overridden method can be accessed
using super.

UNIT-II 23
class A{
int i, j;
void show( ){
System.out.println(“This is in A’s show “);
}}
class B extends A{
int p, q;
void show( ){
super.show( );
System.out.println(“This is in B’s show “);
}}
class Override{
public static void main(String args[ ]){
A obj1=new A( );
B obj2=new B( );
obj1.show( );
obj2.show( );
}}
Sample program: Method Overriding
O/P:
This is in A’s show
This is in A’s show
This is in B’s show

UNIT-II 24
Dynamic Method Dispatch:
Dynamic method dispatch is the mechanism by which a call to an overridden
function is resolved at run time, rather than compile time.
Java implements run-time polymorphism using dynamic method dispatch.

UNIT-II 25
class A {
void callme( ) {
System.out.println("A's method");
}
}
class B extends A {
void callme( ) {
System.out.println("B's method");
}
}
class C extends A {
void callme( ) {
System.out.println("C's method");
}
}
class DynamicMethodDispatch {
public static void main(String args[]) {
A a1=new A( );
B b1=new B( );
C c1=new C( );
A p1;
p1=a1;
p1.callme( );
p1=b1;
p1.callme( );
p1=c1;
p1.callme();
}
}
Sample program: Dynamic Method Dispatch
O/P:-
A’s method
B’s method
C’s method

UNIT-II 26
Abstract classes:
An abstract method is a method without implementation.
The general form is:
abstract type name(parameter-list);
Abstract methods must be overridden(implemented) in the subclasses.
Any class that contains one or more abstract methods must be declared
abstract.
An abstract class cannot be directly instantiated with the new keyword.
We cannot declare abstract constructors or abstract static methods.
Any subclass of an abstract class must either implement all of the abstract
methods in the superclass or be itself declared abstract.
An abstract class reference can point to a subclass object.

UNIT-II 27
abstract class A
{
void show( )
{
System.out.println("A's show method");
}
abstract void display(int x,int y);
}
class B extends A
{
void m1( )
{
System.out.println("Method m1");
}
void display(int x, int y)
{
System.out.println("Param1="+x+
" Param2="+y);
}
}
Sample program1: Abstract classes
O/P:-
Param1=10 Param2=20
class AbstractClass
{
public static void main(String args[ ])
{
B b1=new B();
b1.display(10,20);
}
}

UNIT-II 28
Sample program2: Abstract classes
class AbstractClass2
{
public static void main(String args[ ])
{
B b1=new B( );
b1.display(10,20);
A a1;
a1=b1;
a1.display(30,40);
}
}
O/P:-
Param1=10 Param2=20
Param1=30 Param2=40
abstract class A
{
void show( )
{
System.out.println("A's show method");
}
abstract void display(int x,int y);
}
class B extends A
{
void m1( )
{
System.out.println("Method m1");
}
void display(int x, int y)
{
System.out.println("Param1="+x+
" Param2="+y);
}
}

UNIT-II 29
final keyword:
final can be applied for variables, methods and classes.
A final variable is a constant.
Methods declared as final cannot be overridden.
Classes declared as final cannot be inherited.
Declaring a class as final implicitly declares all of its methods as final.

UNIT-II 30
Base class Object :
Object class contains the following methods:
Object clone( )
boolean equals(Object object)
void finalize( )
Class getClass( )
int hashCode( )
void notify( )
void notifyAll( )
String toString( )
void wait( )
void wait(long milliseconds)
void wait(long milliseconds, int nanoseconds)
Object is superclass of all other classes.

UNIT-II
Method Purpose
Object clone( ) Creates a new object that is the same as the object
being cloned.
boolean equals(Object object) Determines whether one object is equal to
another.
void finalize( ) Called before an unused object is recycled.
Class getClass( ) Obtains the class of an object at run time.
int hashCode( ) Returns the hash code associated with the invoking
object.
void notify( ) Resumes execution of a thread waiting on the
invoking object.
void notifyAll( ) Resumes execution of all threads waiting on the
invoking object.
String toString( ) Returns a string that describes the object.
void wait( )
void wait(long milliseconds)
void wait(long milliseconds, int nanoseconds) Waits on another thread of
exec

UNIT-II 32
Subclass, Subtype and Substitutability:
When new classes are constructed using inheritance from existing
classes, the argument used to justify the validity of substitutability is
as follows:
• Instances of the subclass must possess all data fields associated with
the parent class
• Instances of the subclass must implement, through inheritance atleast
all functionality defined for the parent class.
• An instance of a child class can mimic the behavior of the parent class
and should be indistinguishable from an instance of the parent class if
substituted in a similar situation.

UNIT-II 33
Subclass, Subtype and Substitutability:
The term subtype is used to describe the relationship between types
that explicitly recognizes the principle of substitution.
Type B is considered to be a subtype of A if two conditions hold
•An instance of B can legally be assigned to a variable declared as type
A.
•This value can then be used by the variable with no observable change
in
behavior.
The term subclass refers to the mechanism of constructing a new
class using inheritance.

UNIT-II 34
Interfaces:
Interfaces are similar to classes, but they lack instance variables and their
methods are declared without any body.
The general form of an interface is:
access interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1=value;
type final-varname2=value;
// …
return-type method-nameN(parameter-list);
type final-varnameN=value;
}
Using interface, we can specify what a class must do, but not how it does it.
An interface is defined like a class using the keyword interface.

UNIT-II 35
Interfaces:
Variables declared inside an interface are implicitly final and static.
interface A
{
int i=10;
void firstMethod( );
}
Example1: Interface
All methods and variables are implicitly public if the interface is declared
as public.

UNIT-II 36
Implementing Interfaces:
The methods that implement an interface must be declared public.
One (or) more classes can implement an interface.
To implement an interface, include the implements clause in a class definition
and create the methods contained by the interface.
The general form of a class with implements clause is:
class classname [extends superclass] [implements interface1[,interface2...]]
{
//class body
}

UNIT-II 37
Example2: Implementing Interfaces
interface A
{
int i=10;
void firstMethod();
}
class P implements A
{
public void firstMethod( )
{
System.out.println("This is firstMethod");
}
void display( )
{
System.out.println("This is display");
}
}
class InterfaceDemo1
{
public static void main(String args[ ])
{
P p1=new P();
p1.firstMethod();
}
}
O/P:
This is firstMethod

UNIT-II 38
Example3: Accessing Implementations Through Interface
References
class InterfaceDemo2
{
public static void main(String args[ ])
{
P p1=new P( );
A a1;
a1=p1;
a1.firstMethod();
}
}
O/P:
This is firstMethod
interface A
{
int i=10;
void firstMethod();
}
class P implements A
{
public void firstMethod( )
{
System.out.println("This is firstMethod");
}
void display( )
{
System.out.println("This is display");
}
}

UNIT-II 39
Extending Interfaces:
One interface can inherit another by use of the keyword extends.
The syntax is:
interface interface-name2 extends interface-name1
{
// variables and methods
}

UNIT-II 40
Example4: Extending Interfaces
interface InterOne {
void firstMethod( );
void secondMethod( );
}
interface InterTwo extends InterOne {
void thirdMethod( );
void fourthMethod( );
}
class InterfaceDemo2 {
public static void main(String args[ ]) {
Test t1=new Test( );
t1.firstMethod( );
t1.secondMethod( );
t1.thirdMethod( );
t1.fourthMethod( );
}
}
class Test implements InterTwo {
public void firstMethod( ) {
System.out.println("firstMethod");
}
public void secondMethod( ) {
System.out.println("secondMethod");
}
public void thirdMethod( ) {
System.out.println("thirdMethod");
}
public void fourthMethod( ) {
System.out.println("fourthMethod");
}
void display( ) {
System.out.println("This is display");
}
}

UNIT-II 41
Java file:
A Java source file can contain any (or) all of the following four internal parts:
• A single package statement ( optional )
• Any number of import statements ( optional )
• A single public class declaration
• Any number of classes private to the package ( optional )

UNIT-II 42
Packages:
Packages are containers for classes.
Packages are stored in a hierarchical manner.
Packages are explicitly imported into class definitions.

UNIT-II 43
Creating a Package:
Java uses file system directories to store packages.
The .class files for any classes to be part of a package must be stored in a
directory with the same name of the package.
The directory name must match the package name.
Steps for creating user-defined packages:
1.Select a name for the package.
2.Create a directory with the package name.
3.Write the Java source file with the required classes which are to be a
part of the package. The first statement in the Java source file must be
the package statement and the syntax is:
package pack-name;
4. Compile the Java source file such that the .class files are stored in the
package directory.

UNIT-II

UNIT-II 45
Access specifiers:
PrivateNo modifierProtectedPublic
Same class
Same package
subclass
Same package
non-subclass
Different package
subclass
Different package
non-subclass
Yes Yes Yes Yes
Yes Yes Yes
Yes
Yes
Yes
Yes
Yes
Yes
No
No
No
No
No
No No

UNIT-II 46
Example: Create a package
Create a package with three classes Arithmetic, Bitwise and Logical.
Arithmetic class containing methods to perform arithmetic operations.
Similarly Bitwise and Logical classes.
Let the two classes Arithmetic and Bitwise be public and Logical be without
any access specifier.
Declare some of the methods of Arithmetic class to public and other to
private.
Declare some methods of Bitwise class to protected and other without
access specifier.
Declare the methods of Logical class each with one access specifier.
Now write two java applications using the methods of classes in the
above package.
One program outside the package and the other in the same package.

UNIT-II 47
package pack1;
public class Arithmetic {
public int add(int a,int b) {
return a+b;
}
public int sub(int a,int b) {
return a-b;
}
public int mul(int a,int b) {
return a*b;
}
private int div(int a,int b) {
return a/b;
}
private int mod(int a,int b) {
return a%b;
}
}
Arithmetic class:

UNIT-II 48
Bitwise class:
package pack1;
public class Bitwise {
protected int and(int a,int b) {
return a&b;
}
protected int or(int a,int b) {
return a|b;
}
protected int not(int a) {
return ~a;
}
int xor(int a,int b) {
return a^b;
}
int rightShift(int a,int b) {
return a>>b;
}
}

UNIT-II 49
Logical class:
package pack1;
class Logical {
public boolean shortAnd(boolean x, boolean y) {
return x&&y;
}
private boolean shortOr(boolean x, boolean y) {
return x||y;
}
protected boolean not(boolean x) {
return !x;
}
boolean xor(boolean x, boolean y) {
return x^y;
}
}

UNIT-II 50
Hierarchy of packages:
A package can contain sub packages in it.
The general form is:
package pkg1[.pkg2[.pkg3]];

UNIT-II 51
static import:
The general form is:
import static packagename.classname.staticmembername;
import static packagename.classname.*;
Enable to refer to imported static members as if they were declared in the class
that uses them.

UNIT-II 52
Forms of Inheritance:
Inheritance is employed in a variety of ways.
The various forms of inheritance:
Inheritance for Specialization
Inheritance for Specification
Inheritance for Construction
Inheritance for Extension
Inheritance for Limitation
Inheritance for Combination

UNIT-II 53
Forms of Inheritance:
Inheritance for Specialization: The child is special case of the parent
class.
Inheritance for Specification: The parent class defines behavior that is
implemented in the child class but not in the parent class.
Inheritance for Construction: The child class makes use of the behavior
provided by the parent class but is not a subtype of the parent class.
Inheritance for Extension: The child class adds new functionality to the
parent class, but does not change any inherited behavior.
Inheritance for Limitation: The child class restricts the use of some of the
behavior inherited from the parent class.
Inheritance for Combination: The child class inherits features from more
than one parent class.

UNIT-II 54
Benefits of Inheritance:
Some of the important benefits of inheritance:
Software Reusability
Increased Reliability
Code Sharing
Consistency of Interface
Software Components
Rapid Prototyping
Polymorphism and Frameworks
Information Hiding

UNIT-II 55
Costs of Inheritance:
Although the benefits of inheritance are great, almost nothing is without
cost of one sort or another.
Some of the costs of inheritance are:
Execution Speed
Program Size
Message-Passing Overhead
Program Complexity

56UNIT-II

The Java I/O Classes and Interfaces:
57UNIT-II

The Java I/O Classes and Interfaces:
58UNIT-II

File:
The File class does not specify how information is retrieved from or
stored in files; it describes the properties of a file itself.
A File object is used to obtain or manipulate the information associated
with a disk file, such as the permissions, time, date, and directory path,
and to navigate subdirectory hierarchies.
A directory in Java is treated simply as a File with one additional
property—a list of filenames that can be examined by the list( ) method.
The following constructors can be used to create File objects:
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URI uriObj)
59UNIT-II

booleancanRead( )  inthashCode( )
 booleancanWrite( )  booleanisDirectory( )
 intcompareTo(File pathname)  booleanisFile( )
 booleancreateNewFile( )  booleanisHidden( )
 booleandelete( )  longlastModified( )
 voiddeleteOnExit( )  longlength( )
 booleanequals(Object obj)  String[ ]list( )
 booleanexists( )  File[ ]listFiles( )
 StringgetName( )  booleanmkdir( )
 StringgetParent( )  booleanrenameTo(File dest)
 FilegetParentFile( )  booleansetLastModified(long time)
 StringgetPath( )  booleansetReadOnly( )
 StringtoString( )
Some methods in File class:
60UNIT-II

In Java, input and output is defined in terms of an abstract concept
called "stream".
 
A stream is a sequence of data.
 
If it is an input stream, it has source.
 
If it is an output stream, it has a destination.
 

There are two kinds of streams:
byte streams
character streams
The java.io package provides a large number of classes to perform
stream I/O.
 
The Java I/O Streams:
61UNIT-II

Byte streams and Character streams:
Java’s stream-based I/O is built upon four abstract classes:
InputStream
OutputStream
Reader
Writer
InputStream and OutputStream are designed for byte streams.
Reader and Writer are designed for character streams.
62UNIT-II

The Java I/O Classes and Interfaces:
63UNIT-II

InputStream class:
64UNIT-II

OutputStream class:
65UNIT-II

Reader class:
66UNIT-II

Writer class:
67UNIT-II

 intavailable( )
 voidclose( )
 voidmark(int readlimit)
 booleanmarkSupported( )
abstract  intread( )
 intread(byte[ ] b)
 intread(byte[ ] b, int off, int len)
 voidreset( )
 longskip(long n)
Methods of InputStream class:
68UNIT-II

Class FileInputStream:
A FileInputStream obtains input bytes from a file in a file system.
Constructors:
FileInputStream(File
 file)
FileInputStream(String
 name)
intavailable( )
 voidclose( )
protected  voidfinalize( )
 intread( )
 intread(byte[ ] b)
 intread(byte[ ] b, int off, int len)
 longskip(long n)
Some methods:
69UNIT-II

import java.io.*;
class FileInputStreamDemo
{
public static void main(String args[ ]) throws IOException
{
FileInputStream f1=new FileInputStream("Sample.java");
int a=f1.available( );
System.out.println("Total Available bytes:"+a);
for(int i=1;i<=a;i++)
System.out.print((char)f1.read( ));
f1.close( );
FileInputStream f2=new FileInputStream("Sample.java");
byte b[ ]=new byte[20];
int x=f2.read(b);
for(int i=0;i<b.length;i++)
System.out.print((char)b[i]);
f2.close( );
}
}
FileInputStream: Example program
70UNIT-II

UNIT-II

Class ByteArrayInputStream:
A ByteArrayInputStream contains an internal buffer(byte array) that
contains bytes that may be read from the stream.
Constructors:
ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)
intavailable( )
 voidclose( )
 voidmark(int readAheadLimit)
 booleanmarkSupported( )
 intread( )
 intread(byte[ ] b, int off, int len)
 voidreset( )
 longskip(long n)
Some methods:
72UNIT-II

import java.io.*;
class ByteArrayInputStreamDemo
{
public static void main(String args[ ]) throws IOException
{
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[ ] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0,3);
int c;
while ((c = input1.read( )) != -1)
{
System.out.print((char) c);
}
while ((c = input2.read( )) != -1)
{
System.out.print((char) c);
}
}
}
ByteArrayInputStream: Example Program
73UNIT-II

Filtered Byte Streams:
This class is the superclass of all classes that filter input streams.

These streams sit on top of an already existing input stream
(the underlying input stream), but provide additional functionality.
The class FilterInputStream itself simply overrides all methods of
InputStream with versions that pass all requests to the underlying
input stream.
Subclasses of FilterInputStream may further override some of these
methods as well as provide additional methods and fields.
74UNIT-II

BufferedInputStream:
The class implements a buffered input stream.
By setting up such an input stream, an application can read bytes from a
stream without necessarily causing a call to the underlying system for each
byte read.
The data is read by blocks into a buffer; subsequent reads can access
the data directly from the buffer.
Constructors:
BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize)
BufferedInputStream also supports the mark( ) and reset( ) methods.
75UNIT-II

BufferedInputStream: Example Program
import java.io.*;
class BufferedInputStreamDemo
{
public static void main(String args[]) throws IOException
{
String s = "THIS ON BUFFEREDINPUTSTREAM CLASS";
byte buf[ ] = s.getBytes( );
ByteArrayInputStream in = new ByteArrayInputStream(buf);
BufferedInputStream f = new BufferedInputStream(in);
boolean m=f.markSupported( );
System.out.println("Mark:"+m);
}
}
76UNIT-II

PushbackInputStream:
This class is an input stream filter that provides a buffer into which data
can be "unread."
An application may unread data at any time by pushing it back into the buffer.
Constructors:
PushbackInputStream(InputStream inputStream)
PushbackInputStream(InputStream inputStream, int numBytes)
PushbackInputStream provides
void unread(int ch)
void unread(byte buffer[ ])
void unread(byte buffer, int offset, int numChars)
77UNIT-II

PushbackInputStream: Example Program
78UNIT-II
import java.io.*;
class PushbackDemo
{
public static void main(String args[]) throws IOException
{
byte b[ ]={65,66,67,68,69,70,71,72,73,74,75,76,77,78};
ByteArrayInputStream bs1=new ByteArrayInputStream(b);
PushbackInputStream p1=new PushbackInputStream(bs1);
System.out.println("Total Available bytes in p1:"+p1.available( ));
int ch=p1.read( );
System.out.println((char)ch);
ch=p1.read( );
System.out.println((char)ch);
p1.unread(ch);
ch=p1.read( );
System.out.println((char)ch);
p1.close( );
}
}

SequenceInputStream:
The sequence input stream class allows an application to combine
several input streams serially and make them appear as if they
were a single input stream.
Constructors:
SequenceInputStream(InputStream first, InputStream second)
SequenceInputStream(Enumeration streamEnum)
79UNIT-II

SequenceInputStream: Example Program
import java.io.*;
class SequenceStreamsDemo
{
public static void main(String args[]) throws IOException
{
FileInputStream f2=new FileInputStream("Sample.java");
byte buf[ ]={65,66,67,68,69,70,71,72,73,74,75,76,77,78};
ByteArrayInputStream bs2=new ByteArrayInputStream(buf);
SequenceInputStream s1=new SequenceInputStream(f2,bs2);
System.out.println("Total Available bytes in s1:"+s1.available( ));
for(int i=1;i<=160;i++)
System.out.print((char)s1.read( ));
}
}
80UNIT-II

The PrintStream class provides all of the formatting capabilities we have
been using from the System file handle, System.out.
Constructors:
PrintStream(OutputStream outputStream)
PrintStream(OutputStream outputStream, boolean flushOnNewline)
Java’s PrintStream objects support the print( ) and println( ) methods
for all types, including Object.
If an argument is not a simple type, the PrintStream methods will call the
object’s toString( ) method and then print the result.
PrintStream:
81UNIT-II

OutputStream class:
82UNIT-II

voidclose( )
 voidflush( )
 voidwrite(byte[ ] b)
 voidwrite(byte[ ] b, int off, int len)
abstract  voidwrite(int b).
Methods of OutputStream class:
83UNIT-II

A file output stream is an output stream for writing bytes to a file.
FileOutputStream:
Constructors:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
84UNIT-II

import java.io.*;
class FileOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
FileOutputStream f1=new FileOutputStream("Sample.java");
byte b[ ]={65,66,67,68,69,70,71,72,73,74,75,76,77,78};
f1.write(65);
f1.write(b);
f1.close();
FileOutputStream f2=new FileOutputStream("Sample.java",true);
f2.write(65);
f2.write(b);
f2.close();
}
}
FileOutputStream: Example program
85UNIT-II

ByteArrayOutputStream:
ByteArrayOutputStream is an implementation of an output stream
that uses a byte array as the destination.
Constructors:
ByteArrayOutputStream( )
ByteArrayOutputStream(int numBytes)
In the first form, a buffer of 32 bytes is created.
In the second, a buffer is created with a size equal to that specified by
numBytes.
The buffer is held in the protected buf field of ByteArrayOutputStream.
The buffer size will be increased automatically, if needed.
The data can be retrieved using toByteArray( ) and toString( ).
86UNIT-II

import java.io.*;
class ByteArrayOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
ByteArrayOutputStream bs1 = new ByteArrayOutputStream( );
String s = "This should end up in the array";
byte buf[ ] = s.getBytes( );
bs1.write(buf);
System.out.println("Buffer as a string");
System.out.println(bs1.toString( ));
bs1.close( );
}
}
ByteArrayOutputStream: Example program
87UNIT-II

The class implements a buffered output stream.
By setting up such an output stream, an application can write bytes to the
underlying output stream without necessarily causing a call to the
underlying system for each byte written.
The data is written into a buffer, and then written to the underlying stream
if the buffer reaches its capacity, the buffer output stream is closed,
or the buffer output stream is explicity flushed.
BufferedOutputStream:
Constructors:
BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int bufSize)
88UNIT-II

Reader class:
89UNIT-II

Reader class:
abstract
void
close( )
 voidmark(int readAheadLimit)
 booleanmarkSupported( )
 intread( )
 intread(char[ ] cbuf)
abstract  intread(char[ ] cbuf, int off, int len)
 booleanready( )
 voidreset( )
 longskip(long n)
90UNIT-II

Writer class:
91UNIT-II

abstract voidclose( )
abstract  voidflush( )
 voidwrite(char[ ] cbuf)
abstract  voidwrite(char[ ] cbuf, int off, int len)
 voidwrite(int c)
 voidwrite(String str)
 voidwrite(String str, int off, int len)
Writer class:
92UNIT-II

Serialization:
Serialization is the process of saving an object in a storage medium
(such as a file, or a memory buffer) or to transmit it over a network connection
 
in binary form.
 
The serialized objects are JVM independent and can be re-serialized
by any JVM.
In this case the "in memory" java objects state are converted into a
byte stream.
This type of the file can not be understood by the user.
This process of serializing an object is also called deflating or
marshalling an object.
93UNIT-II

Serialization:
Some of the classes and interfaces related to serialization.
Interfaces:
Serializable
ObjectOutput (extends DataOutput)
DataOutput
ObjectInput (extends DataInput)
DataInput
Classes:
ObjectOutputStream(extends OutputStream implements ObjectOutput)
ObjectInputStream (extends InputStream implements ObjectInput)
94UNIT-II

ObjectOutputStream:
95UNIT-II

ObjectInputStream:
96UNIT-II
Tags