0% found this document useful (0 votes)
10 views

OOP thr Java-UNIT 2

This document covers key concepts of Object-Oriented Programming (OOP) in Java, focusing on inheritance, packages, and interfaces. It explains various types of inheritance such as single, multi-level, hierarchical, and hybrid inheritance, along with examples to illustrate these concepts. Additionally, it discusses the principles of substitutability and polymorphism, and the differences between classes and interfaces.
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)
10 views

OOP thr Java-UNIT 2

This document covers key concepts of Object-Oriented Programming (OOP) in Java, focusing on inheritance, packages, and interfaces. It explains various types of inheritance such as single, multi-level, hierarchical, and hybrid inheritance, along with examples to illustrate these concepts. Additionally, it discusses the principles of substitutability and polymorphism, and the differences between classes and interfaces.
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/ 66

OOP through Java UNIT-2

UNIT-II

Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass,
subtype, substitutability, forms of inheritance specialization, specification, construction,
extension, limitation, combination, benefits of inheritance, costs of inheritance. Member
access rules, super uses, using final with inheritance, polymorphism- method overriding,
abstract classes, the Object class. Defining, Creating and Accessing a Package, Understanding
CLASSPATH, importing packages, differences between classes and interfaces, defining an
interface, implementing interface, applying interfaces, variables in interface and extending
interfaces. Exploring java.io.

Inheritance
Inheritance is one of the corner stones of Object-oriented programming. Because it
allows hierarchical classifications. In terminology of java, a class that is inherited is
called a super class. The class that does the inheriting is called a subclass. Therefore,
a subclass is a specialized version of super class. It inherits all of the instance
variables and methods defined by the super class and adds its own, unique
elements.

Hierarchical abstractions
A powerful way to manage abstraction is through the use of hierarchical classification. This
allows to break the complex systems into manageable pieces.

The inheritance is a very useful and powerful concept of object-oriented


programming. In java, using the inheritance concept, we can use the existing
features of one class in another class. The inheritance provides a great advantage
called code re-usability. Withthe help of code re-usability, the commonly used code
in an application need not be written again and again

For example, a car is a single object for outside but the car consists of several subsystems
such as steering, breaks, sound system, seat belts etc. Again, the sound system consists of
radio, DVD player etc. Here we manage the complexity of a car system through the use of
hierarchical classification. Here everything we view in this world is an object. The topmost
hierarchy for every object is material object.

Base class: Suppose in the above example, car is the base class. and the sub classes are
steering, breaks, engine etc. The behaviour of the child class is always an extension of the
properties of the associated with the parent class.

Subclass: Consider the relationship associated with the parent class and subclass.
 Instances of a sub class must possess all the data areas associated with the parent
class.
 Instances of a sub-class must implement through inheritance at least some or all
functionalities defined for the parent class.
 Thus, an instance of a child class can mime the behaviour of the parent class and
should be indistinguishable from the instance of parent class if substituted in similar
situation. This creates a problem because we use so many forms of inheritance. To
solve this, we use principle of substitutability.

P.Ramesh, Assistant Professor,AIML Dept, TKREC 1


OOP through Java UNIT-2

Substitutability: “The principle of substitutability” says that if we have two classes ‘A’
and ‘B’ such that class B is sub-class of A class, it should be possible to substitute instances of
class B for instance of class A in any situation with no observable effect.

Subtype: The term subtype often refers to a subclass relationship in which the principle of
substitutability is maintained. Statically typed languages (C++) place much more emphasis
on principle of substitutability than dynamically typed languages (Small Talk)

The reason for this is the statically typed languages tend to characterize objects by their class
and dynamically typed languages tend to characterize by behaviour. That is the subtype us
determined in statically typed languages by their class and dynamically typed languages by
their behaviour.

The general form of a class declaration that inherits a superclass is shown here:

class subclass-name extends superclass-name


{
// body of class
}

The following program creates a superclass called A and a subclass called B. Notice
how the keyword extends is used to create a subclass of A.

Example
// A simple example of inheritance. Create a superclass.
class A
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
System.out.println("k: " + k);
}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
P.Ramesh, Assistant Professor,AIML Dept, TKREC 2
OOP through Java UNIT-2
{
A superObj = new A();
B subObj = new B();

// The superclass may be used by itself.


superObj.i = 10;
superObj.j = 20;
System.out.println("Contents of superObj: ");
superObj.showij();
System.out.println();

/* The subclass has access to all public members of its superclass. */


subObj.i = 7;
subObj.j = 8;
subObj.k = 9;
System.out.println("Contents of subObj: ");
subObj.showij();
subObj.showk();
System.out.println();
System.out.println("Sum of i, j and k in subObj:");
subObj.sum();
}
}

OUTPUT
D:\TKREC\Java>java SimpleInheritance
Contents of superObj:
i and j: 10 20

Contents of subObj:
i and j: 7 8
k: 9

Sum of i, j and k in subObj:


i+j+k: 24

Types of Inheritance: When deriving a class from a base class, the base class
may be inherited through public, protected or private inheritance.

Creating Child Class in java: In java, we use the keyword extends to create a
child class. Inheritance represents the IS-A relationship.
The following syntax used to create a child class in java.

Syntax
class <ChildClassName> extends <ParentClassName>
{
//Implementation of child class
}
In a java programming language, a class extends only one class. Extending
multipleclasses is not allowed in java.
P.Ramesh, Assistant Professor,AIML Dept, TKREC 3
OOP through Java UNIT-2

Single inheritance: In a class hierarchy when a child has one and only one
parent and parent has one only child, that inheritance is said to be single
inheritance.

Example
class Student
{
int rollno;
void getNo(int no)
{
rollno=no;
}
void putNo()
{
System.out.println("rollno="+rollno);
}
}
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("Marks = "+marks);
}
}
class SingleInheritance
{
public static void main(String ar[])
{
Marks obj=new Marks();
obj.getNo(546);
obj.putNo();
obj.getMarks(66);
obj.putMarks();
}
}

P.Ramesh, Assistant Professor,AIML Dept, TKREC 4


OOP through Java UNIT-2

OUTPUT
D:\TKREC\Java>java SingleInheritance
Rollno= 546
Marks= 66.0

Example2
//super class
class A
{
int a=10;
int b=20;
}
//intermediate sub class
class add extends A
{
int sum()
{
return a+b;
}
}
public class Single
{
public static void main(String args[])
{
add obj=new add();
int x;
x=obj.sum();
System.out.println(x);
}
}
OUTPUT
D:\TKREC\Java>java Single
Sum is:30

Multiple inheritance: In multiple inheritance, a single subclass extends from multiple super
classes. Java does not support multiple inheritances due to ambiguity. For example, consider
the following Java program.
Note: Java doesn't support multiple inheritance. However, we can achieve multiple
inheritance using interfaces.

P.Ramesh, Assistant Professor,AIML Dept, TKREC 5


OOP through Java UNIT-2

Java does not support multiple inheritances due to ambiguity. For example, consider the
following Java program.

Example
class A
{
void message()
{
System.out.println("All the Best");
}
}
class B
{
void message()
{
System.out.println("Happy Birthday");
}
}
public class Demo extends A,B //considering a scenario
{
public static void main(String args[])
{
Demo obj=new Demo();
//can't decide which classes' message() method will be invoked
obj.message();
}
}
OUTPUT
D:\TKREC\Java>javac Demo.java
Demo.java:15 error :’{‘ expected
Public class demo extends A, B // considering a scenario
1 error

The above code gives error because the compiler cannot decide which message() method is
to be invoked. Due to this reason, Java does not support multiple inheritances at the class
level but can be achieved through an interface.

Multi-level inheritance: In a class hierarchy, when a class is derived from already derived
class then that inheritance is said to be multi-level inheritance

P.Ramesh, Assistant Professor,AIML Dept, TKREC 6


OOP through Java UNIT-2
Example
class Student
{
int rollno;
void getNo(int no)
{
rollno=no;
}
void putNo()
{
System.out.println("Rollno= "+rollno);
}
}
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("Marks= "+marks);
}
}
class Sports extends Marks
{
int score;
void getScore(int scr)
{
score=scr;
}
void putScore()
{
System.out.println("Score= "+score);
}
}

class MultilevelInheritance
{
public static void main(String ar[])
{
Sports obj=new Sports();
obj.getNo(548);
obj.putNo();
obj.getMarks(75);
obj.putMarks();
obj.getScore(100);
obj.putScore();
}

P.Ramesh, Assistant Professor,AIML Dept, TKREC 7


OOP through Java UNIT-2
}
OUTPUT
D:\TKREC\Java>java MultilevelInheritance
Rollno= 548
Marks= 75.0
Score= 100

Example2
//super class
class A
{
int a=10;
int b=20;
}
//intermediate sub class
class add extends A
{
int sum()
{
return a+b;
}
}
//intermediate sub class
class sub extends add
{
int sub()
{
return a-b;
}
}

public class Multilevel


{
public static void main(String args[])
{
add a=new add();
sub s=new sub();
int x,y;
x=a.sum();
System.out.println("The Sum is: "+x);
y=s.sub();
System.out.println("The Subtraction is: "+y);
}
}
OUTPUT
D:\TKREC\Java>java Multilevel
The Sum is: 30
The Subtraction is: -10

P.Ramesh, Assistant Professor,AIML Dept, TKREC 8


OOP through Java UNIT-2
Hierarchical inheritance: In a class hierarchy, when a parent class has two or more
than two child classes then, the inheritance is said to be hierarchical inheritance.

Example
class Student
{
int rollno;
void getNo(int no)
{
rollno=no;
}
void putNo()
{
System.out.println("Rollno= "+rollno);
}
}
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("Marks= "+marks);
}
}
class Sports extends Student
{
int score;
void getScore(int scr)
{
score=scr;
}
void putScore()
{
System.out.println("Score= "+score);
}

P.Ramesh, Assistant Professor,AIML Dept, TKREC 9


OOP through Java UNIT-2
}

class HierarchicalInheritance
{
public static void main(String ar[])
{
Marks m=new Marks();
Sports s=new Sports();
m.getNo(548);
m.putNo();
m.getMarks(75);
m.putMarks();
s.getNo(548);
s.putNo();
s.getScore(100);
s.putScore();
}
}
OUTPUT
D:\TKREC\Java>java HierarchicalInheritance
Rollno= 548
Marks= 75.0
Rollno= 548
Score= 100

Example2
//super class
class A
{
int a=30;
int b=10;
}
//intermediate sub class
class add extends A
{
int sum()
{
return a+b;
}
}
//intermediate sub class
class sub extends A
{
int sub()
{
return a-b;
}
}
//intermediate sub class
class mul extends A

P.Ramesh, Assistant Professor,AIML Dept, TKREC 10


OOP through Java UNIT-2
{
int mul()
{
return a*b;
}
}
public class Hierarchical
{
public static void main(String args[])
{
add a=new add();
sub s=new sub();
mul m=new mul();
int x,y,z;
x=a.sum();
System.out.println("Sum is: "+x);
y=s.sub();
System.out.println("Subtraction is: "+y);
z=m.mul();
System.out.println("Multiplication is: "+z);
}
}
OUTPUT
D:\TKREC\Java>java Hierarchical
Sum is: 40
Subtraction is: 20
Multiplication is: 300

Hybrid inheritance: It is a combination of two or more types of inheritance. Here,


we have combined hierarchical and multiple inheritance to form a hybrid
inheritance.

Example
//super class
class A
{
int a=20;

P.Ramesh, Assistant Professor,AIML Dept, TKREC 11


OOP through Java UNIT-2
int b=10;
}
//intermediate sub class
class add extends A
{
int sum()
{
return a+b;
}
}
//intermediate sub class
class sub extends A
{
int sub()
{
return a-b;
}
}
//intermediate sub class
class div extends add
{
int div()
{
return a/b;
}
}
public class Hybrid
{
public static void main(String args[])
{
add a=new add();
sub s=new sub();
div m=new div();
int x,y,z;
x=a.sum();
System.out.println("Sum is: "+x);
y=s.sub();
System.out.println("Subtraction is: "+y);
z=m.div();
System.out.println("Division is: "+z);
}
}
OUTPUT
D:\TKREC\Java>java Hybrid
Sum is: 30
Subtraction is: 10
Division is: 2

P.Ramesh, Assistant Professor,AIML Dept, TKREC 12


OOP through Java UNIT-2

Example2
//parent class
class GrandFather
{
public void show()
{
System.out.println("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
System.out.println("I am father.");
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
System.out.println("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
System.out.println("I am a daughter.");
}
P.Ramesh, Assistant Professor,AIML Dept, TKREC 13
OOP through Java UNIT-2
public static void main(String args[])
{
Daughter obj = new Daughter();
obj.show();
}
}
OUTPUT
D:\TKREC\Java>java Daughter
I am a Daughter

Forms of inheritance
Inheritance is used in variety of ways. The following list represents general abstract
categories and is not intended to be exhaustive.

Sub-classing for Specialization:


The most common use of inheritance and sub-classing is for specialization. In this the
derived class is specialized form of the parent class and satisfies the specifications of the
parent in all relevant aspects. This is the most ideal form of inheritance; something that a
good design should strive for example class window provides general windowing
operations such as moving, resizing etc. A specialized sub class text edit window inherits the
window opens. And in addition provides the windows to display textual material

Example
class Parent
{
int i=10;
void show()
{
System.out.println("i value= "+i);
}
}
class Child extends Parent
{
// show() will be called by Child Object in main class
}
class specialization
{
public static void main(String args[])
{
Child c=new Child();
c.show();
}
}
OUTPUT
D:\Java>java specialization
i value= 10

Sub-classing for Specification:


In the classes maintained a certain common interface i.e, they implement the same methods

P.Ramesh, Assistant Professor,AIML Dept, TKREC 14


OOP through Java UNIT-2
the parent class can be the combination of implemented operations and the operations are
differed to child class. The child merely implements behaviour describe but not implemented
in the parent. In such classes the parent class is mostly known as abstract specification class.

Example
abstract class Parent
{
int i;
abstract void show(); // only specifications
}
class Child extends Parent
{
int i=20;
void show()
{
System.out.println("i value is = "+i);
}
}
class specifications
{
public static void main(String args[])
{
Child c=new Child();
c.show();
}
}
OUTPUT
D:\Java>java specifications
i value is = 20

Sub-classing for Construction:


A class can often inherit, almost all of its desired functionality from the parent
class perhaps changing only the names of the methods used to interface to the
class are modifying the arguments in a certain fashion. This may be true if the
new class and the parent class failed to share the relationship.

Example
class Parent
{
int i=20;
void show()
{
System.out.println("The value of I is = "+i);
}
}
class Child extends Parent
{
int i=30;
void display() // own implementation of child class
{

P.Ramesh, Assistant Professor,AIML Dept, TKREC 15


OOP through Java UNIT-2
System.out.println("i value is = "+i);
}
}
class construction
{
public static void main(String args[])
{
Child c=new Child();
c.show();
c.display();
}
}
OUTPUT
D:\Java>java construction
The value of I is = 20
i value is = 30

Sub-classing for extension


In sub-classing for generalization modifies or extends on the existing
functionality of an object. But sub-classing for extension acts totally new
abilities. In the sub-classing for generalization it must override at least one
method from the parent and here we must at least extend one method of the
parent.

Exaple
class Parent
{
int i=15;
void show()
{
System.out.println("i value is "+i);
}
}

class Child extends Parent


{
// show() will be called by Child Object in main class
void display() // new method is also implemented
{
System.out.println("This is child class");
}
}
class extension
{
public static void main(String args[])
{
Child c=new Child();
c.show();
c.display();
}
P.Ramesh, Assistant Professor,AIML Dept, TKREC 16
OOP through Java UNIT-2
}
OUTPUT
D:\Java>java extension
i value is 15
This is child class

Sub-classing for limitation


Subclassing for limitation occurs when the behaviour of the sub-class is smaller
or more restrictive than the behaviour of the parent class.

Example
class Parent
{
int i=5;
void show()
{
System.out.println("i value = "+i);
}
void display() // new method is also implemented
{
System.out.println("This is Parent class");
}
}

class Child extends Parent


{
// show() will be called by Child Object in main class
// display() may not use .i.e, all methods of Parent will not be used
}

class limitation
{
public static void main(String args[])
{
Child c=new Child();
c.show();
//c.display();
}
}
OUTPUT
D:\Java>java limitation
i value = 5

D:\Java>java limitation
i value = 5
This is Parent class

Subclassing for Combination


A common situation is that a sub class may represent the combination of
features from two or more parent classes.
P.Ramesh, Assistant Professor,AIML Dept, TKREC 17
OOP through Java UNIT-2
For example a class teaching assistant can be desired from both the parent
classes teacher and assistant

Benefits of inheritance
Various benefits of inheritance are

S/w Reusability: Many programmers spend much of their time in rewriting code they have
written many times before. So with inheritance code once written can be reused.

Code sharing: Code sharing occurs at two levels. At first level many users or projects can
use the same class. In the second level sharing occurs when two or more classes developed
by a single programmer as part of a project which is being inherited from a single parent
class. Here also code is written once and reused. This is possible through inheritance.

Consistency of inheritance: When two or more classes inherit from the same superclass we
are assured that the behaviour they inherit will be the same in all cases. Thus we can
guarantee that interfaces to similar objects are in fact similar.

Software components: Inheritance provides programmers the ability to construct reusable


s/w components. The goal behind these is to provide applications that require little or no
actual coding. Already such libraries and packages are commercially available.

Rapid Prototyping: When a s/w system is constructed largely out of reusable components
development can be concentrated on understanding the new and unusual portion of the
system. Thus s/w system can be generated more quickly and easily leading to a style of
programming known as ‘Rapid Prototyping’ or ‘exploratory programming’

Polymorphism and Framework: Generally s/w is written from the bottom up, although it
may be designed from top-down. This is like building a wall where every brick must be laid
on top of another brick i.e., the lower level routines are written and on top of these slightly
higher abstraction are produced and at last more abstract elements are generated.
Polymorphism permits the programmer to generate high level reusable components.

Information Hiding: A Programmer who reuses a software need only to understand the
nature of the component and its interface. There is no need to have detailed information of
the component and it is information hiding.

Costs of inheritance
Although they are benefits with object oriented programming we must also
consider the cost of inheritance.

Execution Speed: The inherited methods which must deal with orbitary sub-
classes are often slower than specialized code. Here efficiency is often misplaced.
It is far better to develop a working system and monitor it.

Program Size: The use of any s/w library imposes a size penalty not imposed by
systems constructed for a specific project. Although the expense may be
substantial and size of program becomes less important.

Message passing overhead: Message passing is costly by nature a more costly


P.Ramesh, Assistant Professor,AIML Dept, TKREC 18
OOP through Java UNIT-2
operation than simple procedure invocation

Program Complexity: Although object oriented programming is often touched


as a solution to s/w complexity. The complexity increases when we use
inheritance. But it is not considerable.

Member Access Rules


As java is an object-oriented programming language, data is given more
importance regarding its access. Data is to be protected against unauthorized
access.

In order to protect data in a well-built way, data is organized into three


categories.
 Public data
 Private data
 Protected data

The following table illustrates the member access rules

 The members declared as public can be accessed any where, any class and
any package.
 The members declared as private can be accessed only by the methods of
same class where the private members are declared.
 The members declared as protected cannot be accessed in non-subclasses
of different packages in rest of the cases they can be accessed. If you want
any member to be accessed in the subclasses of other packages they can be
declared as protected. These members are being protected from the access
facility of non-subclasses of other packages.
 The members declared by nothing, like of no modifier is being placed
before a member of a class then, these members can be access only up to
package. This occurs by default. Different packages are not allowed to
access these no modifier members.

P.Ramesh, Assistant Professor,AIML Dept, TKREC 19


OOP through Java UNIT-2
For example, consider the following simple class hierarchy

Example
/* In a class hierarchy, private members remain private to their class. This
program contains an error and will not compile. */

// Create a superclass.

class A
{
int i; // public by default
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A
{
int total;
void sum()
{
total = i + j; // ERROR, j is not accessible here
}
}
class MemberAccess
{
public static void main(String args[])
{
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
OUTPUT
D:\TKREC\Java>javac MemberAccess.java
MemberAccess.java:20: error: j has private access in A
total = i + j; // ERROR, j is not accessible here
^
1 error

This program will not compile because the reference to j inside the sum( )
method of B causes an access violation. Since j is declared as private, it is only
accessible by other members of its own class. Subclasses have no access to it

Note: A class member that has been declared as private will remain private to
its class. It is not accessible by any code outside its class, including subclasses

P.Ramesh, Assistant Professor,AIML Dept, TKREC 20


OOP through Java UNIT-2

A more practical example that will help illustrate the power of inheritance.
Here, the final version of the Box class developed in the preceding chapter will
be extended to include a fourth component called weight. Thus, the new class
will contain a box’s width, height, depth, and weight.

Example
// This program uses inheritance to extend Box.
class Box
{
double width;
double height;
double depth;

// construct clone of an object


Box(Box ob) // pass object to constructor
{
width = ob.width;
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;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
// Here, Box is extended to include weight.
class BoxWeight extends Box
{
double weight; // weight of box

P.Ramesh, Assistant Professor,AIML Dept, TKREC 21


OOP through Java UNIT-2

// constructor for BoxWeight


BoxWeight(double w, double h, double d, double m)
{
width = w;
height = h;
depth = d;
weight = m;
}
}

class DemoBoxWeight
{
public static void main(String args[])
{
BoxWeight box1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight box2 = new BoxWeight(2, 3, 4, 0.076);

double vol;
vol =box1.volume();
System.out.println("Volume of box1 is " + vol);
System.out.println("Weight of box1 is " + box1.weight);
System.out.println();

vol = box2.volume();
System.out.println("Volume of box2 is " + vol);
System.out.println("Weight of box2 is " + box2.weight);
}
}
OUTPUT
D:\TKREC\Java>java DemoBoxWeight
Volume of box1 is 3000.0
Weight of box1 is 34.3

Volume of box2 is 24.0


Weight of box2 is 0.076

BoxWeight inherits all of the characteristics of Box and adds to them the weight
component. It is not necessary for BoxWeight to re-create all of the features
found in Box. It can simply extend Box to meet its own purposes.

A major advantage of inheritance is that once you have created a superclass


that defines the attributes common to a set of objects, it can be used to
create any number of more specific subclasses. Each subclass can precisely
tailor its own classification.

For example, the following class inherits Box and adds a color attribute

// Here, Box is extended to include color.


class ColorBox extends Box

P.Ramesh, Assistant Professor,AIML Dept, TKREC 22


OOP through Java UNIT-2
{
int color; // color of box
ColorBox(double w, double h, double d, int c)
{
width = w;
height = h;
depth = d;
color = c;
}
}

Super Uses
In java, super is a keyword used to refer to the parent class object. The super
keyword came into existence to solve the naming conflicts in the
inheritance. When both parent class and child class have members with the
same name, then the super keyword is used to refer to the parent class version.

In java, the super keyword is used for the following purposes.


 To refer parent class data members
 To refer parent class methods
 To call parent class constructor

Note: The super keyword is used inside the child class only.

Super to refer parent class data members: When both parent class and child
class have data members with the same name, then the super keyword is used to
refer to the parent class data member from child class.

To call the parameterized constructor of the parent class, the super keyword must
be the first statement inside the child class constructor, and we must pass the
parameter values.

Example

class A
{
int a=10;
}
class B extends A
{
int b=20;
void m1()
{
System.out.println("Value of a in Parent class:" + super.a);
System.out.println("Value of b in Childt class:" + b);
}
}
public class Test
{
public static void main(String args[])
P.Ramesh, Assistant Professor,AIML Dept, TKREC 23
OOP through Java UNIT-2
{
B obj=new B();
obj.m1();
}
}
OUTPUT:
D:\TKREC\Java>java Test
Value of a in Parent class: 10
Value of b in Child class: 20

Super to refer parent class method: When both parent class and child class
havemethod with the same name, then the super keyword is used to refer to the
parent class method from child class.

Example
class A
{
// overridden method
public void display()
{
System.out.println(" This is class A Method ");
}
}
class B extends A
{
// overriding method
public void display()
{
System.out.println(" This is class B Method ");
}

public void printMessage()


{
// this calls overriding method
display();

// this calls overridden method


super.display();
}
}
public class Main
{
public static void main(String args[])
{
B obj=new B();
obj.printMessage();
}
}
OUTPUT:
D:\TKREC\Java>java Main

P.Ramesh, Assistant Professor,AIML Dept, TKREC 24


OOP through Java UNIT-2
This is class B Method
This is class A Method

Super to call parent class constructor: When an object of child class is


created, it automatically calls the parent class default-constructor before its
own. But, theparameterized constructor of parent class must be called explicitly
using the super keyword inside the child class constructor.

Example
class A
{
A()
{
System.out.println(" Base class Constructor ");
}
}

class B extends A
{
B()
{
super();
}
}
public class Test
{
public static void main(String args[])
{
B obj=new B();
}
}
OUTPUT:
D:\TKREC\Java>java Test
Base class Constructor

To call the parameterized constructor of the parent class, the super keyword
must be the first statement inside the child class constructor, and we must pass
the parameter values.

Example
class Teacher
{
// default or no-arg constructor
Teacher()
{
System.out.println("I am a Teacher");
}
// parameterized constructor
Teacher(String name)
{

P.Ramesh, Assistant Professor,AIML Dept, TKREC 25


OOP through Java UNIT-2
System.out.println("The String Name is: "+name);
}
}
class Student extends Teacher
{
// default constructor
Student()
{
// calling parameterized constructor of the superclass
super("Teacher");
System.out.println("I am a Student");
}
}

class Main
{
public static void main(String args[])
{
Student obj = new Student();
}
}
OUTPUT:
D:\TKREC\Java>java Main
The String Name is: Teacher
I am a Student

Using final with inheritance


In java, the final is a keyword and it is used with the following things.
 With variable (to create constant)
 With method (to avoid method overriding)
 With class (to avoid inheritance)

Final with variables: When a variable defined with the final keyword, it
becomes a constant, and it does not allow us to modify the value. The variable
defined with the final keyword allows only a one-time assignment, once a value
assigned to it, never allows us to change it again.

Example
class Finalvariable
{
public static void main(String args[])
{
final int a=10;
a=30;
System.out.println(" The value of a is:" + a);
}
}
OUTPUT:
D:\TKREC\Java>javac Finalvariable.java

P.Ramesh, Assistant Professor,AIML Dept, TKREC 26


OOP through Java UNIT-2
Finalvariable.java:6: error: cannot assign a value to final variable a
a=30;
^
1 error

Final with methods: When a method defined with the final keyword, it does not allow it to
override. The final method extends to the child class, but the child class cannot override or
re-define it. It must be used as it has implemented in the parent class.

Example

class A
{
public final void display()
{
System.out.println(" This is Final Method ");
}
}
class B extends A
{
public final void display()
{
System.out.println(" This is Final Method is overridden ");
}
public static void main(String args[])
{
B obj=new B();
obj.display();
}
}
OUTPUT:
D:\TKREC\Java>javac A.java
A.java:10: error: display() in B cannot override display() in A
public final void display()
^
overridden method is final
1 error

Final with class: When a class defined with final keyword, it cannot be
extended by anyother class.

Example
final class A
{
public void display()
{
System.out.println(" This is Final Method ");
}
}
// try to extend finalclass

P.Ramesh, Assistant Professor,AIML Dept, TKREC 27


OOP through Java UNIT-2
class B extends A
{
public void display()
{
System.out.println(" This is Final Method is overridden ");
}
public static void main(String args[])
{
B obj=new B();
obj.display();
}
}
OUTPUT:
D:\TKREC\Java>javac A.java
A.java:9: error: cannot inherit from final A
class B extends A
^
1 error

Polymorphism
The polymorphism is the process of defining same method with different
implementation.That means creating multiple methods with different behavior.
In java, polymorphism implemented using method overloading and method
overriding.

Ad hoc polymorphism: The ad hoc polymorphism is a technique used to define


the same method with different implementations and different arguments. In a
java programming language, ad hoc polymorphism carried out with a method
overloading concept.

In ad hoc polymorphism the method binding happens at the time of compilation.


Ad hoc polymorphism is also known as compile-time polymorphism. Every
function call binded with the respective overloaded method based on the
arguments.

The ad hoc polymorphism implemented within the class only.

Example
import java.util.Arrays;
public class AdHocPolymorphismExample
{
void sorting(int[] list)
{
Arrays.parallelSort(list);
System.out.println("Integers after sort: " + Arrays.toString(list) );
}
void sorting(String[] names)
{
Arrays.parallelSort(names);
System.out.println("Names after sort: " + Arrays.toString(names) );
P.Ramesh, Assistant Professor,AIML Dept, TKREC 28
OOP through Java UNIT-2
}
public static void main(String[] args)
{
AdHocPolymorphismExample obj = new AdHocPolymorphismExample();
int list[] = {2, 3, 1, 5, 4};
obj.sorting(list); // Calling with integer array
String[] names = {"rama", "raja", "shyam", "seeta"};
obj.sorting(names); // Calling with String array
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java AdHocPolymorphism
Integers after sort: [1, 2, 3, 4, 5]
Names after sort: [raja, rama, seeta, shyam]
Pure polymorphism: The pure polymorphism is a technique used to define the same
method with the same arguments but different implementations. In a java programming
language, pure polymorphism carried out with a method overriding concept.

In pure polymorphism, the method binding happens at run time. Pure polymorphism is also
known as run-time polymorphism. Every function call binding with the respective
overridden method based on the object reference.

When a child class has a definition for a member function of the parent class, the parent
class function is said to be overridden.

The pure polymorphism implemented in the inheritance concept only.

Example
class ParentClass
{
int num = 10;
void showData()
{
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
class ChildClass extends ParentClass
{
void showData()
{
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}

public class PurePolymorphism


{
public static void main(String[] args)

P.Ramesh, Assistant Professor,AIML Dept, TKREC 29


OOP through Java UNIT-2
{
ParentClass obj = new ParentClass();
obj.showData();
// a superclass reference variable can refer to a subclass object
obj = new ChildClass();
obj.showData();
}
}
OUTPUT:
D:\TKREC\Java>java PurePolymorphism
Inside ParentClass showData() method
num = 10
Inside ChildClass showData() method
num = 10

Java Method Overriding


The method overriding is the process of re-defining a method in a child class that is already
defined in the parent class. When both parent and child classes have the same method, then
that method is said to be the overriding method.

The method overriding enables the child class to change the implementation of the method
which acquired from parent class according to its requirement.

In the case of the method overriding, the method binding happens at run time. The method
binding which happens at run time is known as late binding. So, the method overriding
follows late binding.

The method overriding is also known as dynamic method dispatch or run


time polymorphism or pure polymorphism.

Example

class A
{
public void displayInfo()
{
System.out.println(" This is class A method ");
}
}

class B extends A
{
@Override
public void displayInfo()
{
System.out.println("This is class B method ");
}
}

P.Ramesh, Assistant Professor,AIML Dept, TKREC 30


OOP through Java UNIT-2
class Methodoverriding
{
public static void main(String[] args)
{
B obj = new B();
obj.displayInfo();
}
}
OUTPUT:
D:\TKREC\Java>java Methodoverriding
This is class B method

In a class hierarchy, when a method in a subclass has the same name and type signature as
a method in its superclass, then the method in the subclass is said to override the method in
the superclass. When an overridden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass. The version of the method
defined by the superclass will be hidden.

Consider the following:


Example
// Method overriding.
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
// display i and j
void show()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show()
{
System.out.println("k: " + k);
}
}
class Override
P.Ramesh, Assistant Professor,AIML Dept, TKREC 31
OOP through Java UNIT-2
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

OUTPUT:
D:\TKREC\Java>java Override
k: 3

Method overriding occurs only when the names and the type signatures of the two methods
are identical. If they are not, then the two methods are simply overloaded. For example,
consider this modified version of the preceding example:

// Methods with differing type signatures are overloaded – not overridden.

Example
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
// display i and j
void show()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
// overload show()
void show(String msg)
{
System.out.println(msg + k);
}
}
class Override2
{

P.Ramesh, Assistant Professor,AIML Dept, TKREC 32


OOP through Java UNIT-2
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B
subOb.show(); // this calls show() in A
}
}
OUTPUT:
D:\TKREC\Java>java Override2
This is k: 3
i and j: 1 2

A more practical example that uses method overriding. The following program
creates a superclass called Figure that stores the dimensions of a two-
dimensional object. It also defines a method called area( ) that computes the
area of an object. The program derives two subclasses from Figure. The first is
Rectangle and the second is Triangle. Each of these subclasses overrides area( )
so that it returns the area of a rectangle and a triangle, respectively.

// Using run-time polymorphism.

Example
class Figure
{
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);
}
// override area for rectangle
double area()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

P.Ramesh, Assistant Professor,AIML Dept, TKREC 33


OOP through Java UNIT-2
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a, b);
}
// override area for right triangle
double area()
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class FindAreas
{
public static void main(String args[])
{
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);

Figure fg;
fg = r;
System.out.println("Area is " + fg.area());
fg = t;
System.out.println("Area is " + fg.area());
fg = f;
System.out.println("Area is " + fg.area());
}
}
OUTPUT:
D:\TKREC\Java>java FindAreas
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
Area for Figure is undefined.
Area is 0.0

Rules for method overriding


While overriding a method, we must follow the below list of rules.
 Static methods cannot be overridden.
 Final methods cannot be overridden.
 Private methods cannot be overridden.
 Constructor cannot be overridden.
 An abstract method must be overridden.
 Use super keyword to invoke overridden method from child class.
 The return type of the overriding method must be same as the parent has it.
 The access specifier of the overriding method can be changed, but the
visibility must increase but not decrease. For example, a protected method
P.Ramesh, Assistant Professor,AIML Dept, TKREC 34
OOP through Java UNIT-2
in the parent class can be made public, but not private, in the child class.

Dynamic Method Dispatch


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.

An important principle: 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. When different types of objects are referred to, different versions of an
overridden method will be called.

Example
// Dynamic Method Dispatch
class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
// override callme()
void callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{
// override callme()
void callme()
{
System.out.println("Inside C's callme method");
}
}
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
P.Ramesh, Assistant Professor,AIML Dept, TKREC 35
OOP through Java UNIT-2
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:
D:\TKREC\Java>java Dispatch
Inside A's callme method
Inside B's callme method
Inside C's callme method

Java Abstract Class


An abstract class is a class that created using abstract keyword. In other
words, a classprefixed with abstract keyword is known as an abstract class.

In java, an abstract class may contain abstract methods (methods without


implementation) and also non-abstract methods (methods with implementation).

Syntax
abstract class <ClassName>
{
}

To declare an abstract method, use this general form:


abstract type name(parameter-list);

Example
// A Simple demonstration of abstract.
abstract class A
{
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo()
{
System.out.println("This is a concrete method.");
}
}
class B extends A
{
void callme()
{
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
P.Ramesh, Assistant Professor,AIML Dept, TKREC 36
OOP through Java UNIT-2
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}
OUTPUT:
D:\TKREC\Java>java AbstractDemo
B's implementation of callme.
This is a concrete method.

An abstract class cannot be instantiated but can be referenced. That means


we cannot create an object of an abstract class, but base reference can be
created.

Example
abstract class Shape
{
// method of abstract class
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println(" Drawing Rectangle ");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println(" Drawing Circle ");
}
}
public class Main
{
public static void main(String[] args)
{
// create an object of Shape
Shape obj = new Circle();
obj.draw();
}
}
OUTPUT:
D:\TKREC\Java>java Main
Drawing Circle

// Using abstract methods and classes.

P.Ramesh, Assistant Professor,AIML Dept, TKREC 37


OOP through Java UNIT-2
Example
abstract class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a, b);
}
// override area for rectangle
double area()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a, b);
}
// override area for right triangle
double area()
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas
{
public static void main(String args[])
{
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure fg; // this is OK, no object is created
fg = r;
System.out.println("Area is " + fg.area());
fg = t;

P.Ramesh, Assistant Professor,AIML Dept, TKREC 38


OOP through Java UNIT-2
System.out.println("Area is " + fg.area());
}
}
OUTPUT:
D:\TKREC\Java>java AbstractAreas
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0

Rules for Abstract class


 An abstract class must follow the below list of rules.
 An abstract class must be created with abstract keyword.
 An abstract class can be created without any abstract method.
 An abstract class may contain abstract methods and non-abstract
methods.
 An abstract class may contain final methods that cannot be overridden.
 An abstract class may contain static methods, but the abstract
method cannot bestatic.
 An abstract class may have a constructor that gets executed when the
child classobject created.
 An abstract method must be overridden by the child class, otherwise, it
must bedefined as an abstract class.
 An abstract class cannot be instantiated but can be referenced.

Java Object Class


In java, the Object class is the super most class of any class hierarchy. The
Object class in the java programming language is present inside the java.lang
package. Every class in the java programming language is a subclass of Object
class by default.

The Object class is useful when you want to refer to any object whose type you
don't know. Because it is the super class of all other classes in java, it can refer
to any type of object.

There is one special class, Object, defined by Java. All other classes are
subclasses of Object. That is, Object is a superclass of all other classes. This
means that a reference variable of type Object can refer to an object of any other
class. Also, since arrays are implemented as classes, a variable of type Object can
also refer to any array.
Object defines the following methods, which means that they are available in
every object.

Example

class Lamp
{
// stores the value for light
// true if light is on

P.Ramesh, Assistant Professor,AIML Dept, TKREC 39


OOP through Java UNIT-2
// false if light is off
boolean isOn;

// method to turn on the light


void turnOn()
{
isOn = true;
System.out.println("Light on? " + isOn);
}

// method to turnoff the light


void turnOff()
{
isOn = false;
System.out.println("Light on? " + isOn);
}
}
class Main
{
public static void main(String[] args)
{
// create objects led and halogen
Lamp led = new Lamp();
Lamp halogen = new Lamp();

// turn on the light by calling method turnOn()


led.turnOn();

// turn off the light by calling method turnOff()


halogen.turnOff();
}
}
OUTPUT:
D:\TKREC\Java>java Main
Light on? true
Light on? false

Create objects inside the same class


We can also create objects inside the same class. We are creating the object
inside the main() method of the same class

Example
class Lamp
{
// stores the value for light, true if light is on, false if light is off
boolean isOn;

// method to turn on the light


void turnOn()
{

P.Ramesh, Assistant Professor,AIML Dept, TKREC 40


OOP through Java UNIT-2
isOn = true;
System.out.println("Light on? " + isOn);
}
public static void main(String[] args)
{
// create an object of Lamp
Lamp led = new Lamp();
// access method using object
led.turnOn();
}
}

OUTPUT:
D:\TKREC\Java>java Lamp
Light on? true

Methods of Object class


The following table depicts all built-in methods of Object class in java.

Return
Method Description Value

getClass() Returns Class class object object

hashCode() returns the hashcode number for object being used. int

equals(Object compares the argument object to calling object. boolean


obj)

clone() Compares two strings, ignoring case int

concat(String) Creates copy of invoking object object

toString() returns the string representation of invoking object. String

notify() wakes up a thread, waiting on invoking object's void


monitor.

notifyAll() wakes up all the threads, waiting on invoking object's void


monitor.

wait() causes the current thread to wait, until another void


thread notifies.

wait(long,int) causes the current thread to wait for the specified void
milliseconds and nanoseconds, until another thread
notifies.

P.Ramesh, Assistant Professor,AIML Dept, TKREC 41


OOP through Java UNIT-2
finalize() It is invoked by the garbage collector before an object void
is being garbage collected.

Defining, Creating and Accessing a Package


In java, a package is a container of classes, interfaces, and sub-packages. We may
think of it as a folder in a file directory. We use the packages to avoid naming
conflicts and to organize project-related classes, interfaces, and sub-packages into
a bundle.

In java, the packages have divided into two types.

 Built-in Packages
 User-defined Packages

Built-in Packages: The built-in packages are the packages from java API. The
Java API is a library of pre-defined classes, interfaces, and sub-packages. The
built-in packages were included in the JDK.

There are many built-in packages in java, few of them are as java, lang, io,
util, awt, javax, swing, net, sql, etc. We need to import the built-in packages to
use them in our program. To import a package, we use the import statement.

User-defined Packages: The user-defined packages are the packages created


by the user. User is free to create his own packages.

Defining a Package in java


We use the package keyword to create or define a package in java programming
language.

Syntax
package packageName;
The package statement must be the first statement in the program.The package
name must be a single word. The package name must use Camel case notation.

Let's consider the following code to create a user-defined package myPackage.

// To create a user-defined package myPackage


/* To save and run the program
javac -d . DefiningPackage.java & java myPackage.DefiningPackage */

// The -d is represents destination and the. (dot operator) represents the current folder.

Example
package myPackage;
public class DefiningPackage
{
public static void main(String[] args)
{
System.out.println("This class belongs to myPackage.");
P.Ramesh, Assistant Professor,AIML Dept, TKREC 42
OOP through Java UNIT-2
}
}
OUTPUT:
D:\TKREC\Java>javac -d . DefiningPackage.java
D:\TKREC\Java>java myPackage.DefiningPackage
This class belongs to myPackage.
Now, save the above code in a file DefiningPackage.java, and compile it using
thefollowing command.

javac -d . DefiningPackage.java
The above command creates a directory with the package name myPackage,
and the DefiningPackage.class is saved into it. Run the program use the
following command.

java myPackage.DefiningPackage
When we use IDE like Eclipse, Netbeans, etc. the package structure is created
automatically.

Accessing a Packages:

Access Specifier: Specifies the scope of the data members, class and methods.
 Private members of the class are available with in the class only. The
scope of private members of the class is “CLASS SCOPE”.
 Public members of the class are available anywhere. The scope of public
members of the class is "GLOBAL SCOPE".
 Default members of the class are available with in the class, outside the
class and in its sub class of same package. It is not available outside the
package. So the scope of default members of the class is "PACKAGE
SCOPE".
 Protected members of the class are available with in the class, outside the
class and in its sub class of same package and also available to subclasses
in different package also.

The following table provides information about the visibility of both data
members and methods.

P.Ramesh, Assistant Professor,AIML Dept, TKREC 43


OOP through Java UNIT-2

 The public members can be accessed everywhere.


 The private members can be accessed only inside the same class.
 The protected members are accessible to every child class (same package
or otherpackages).
 The default members are accessible within the same package but not
outside thepackage.

Understanding CLASSPATH
If we want to save or keep java source files and class files in different directories
or drives then we need to set the classpath to run or execute those class files

For Example
C:\classes and D:\TKREC\Java now I want to put the class file of
Sample.java Source file in the folder of C: drive

Example
public class Sample
{
public static void main(String args[])
{
System.out.println(" This is Example of setting CLASSPATH ");
}
}

OUTPUT:
To Compile
D:\TKREC\Java>javac -d C:\classes Sample.java

To Run
To run this program for D:\TKREC\Java you need to set classpath of the Directory where the
class file resides

D:\TKREC\Java>set classpath=C:\classes;.;

D:\TKREC\Java>java Sample
This is Example of setting CLASSPATH

Importing Packages in java


In java, the import keyword used to import built-in and user-defined packages.
When a package has imported, we can refer to all the classes of that package
using their name directly.

The import statement must be after the package statement, and before any
other statement. Using an import statement, we may import a specific class
or all the classes from apackage.

Using one import statement, we may import only one package or a class. Using
an import statement, we cannot import a class directly, but it must be a part

P.Ramesh, Assistant Professor,AIML Dept, TKREC 44


OOP through Java UNIT-2
of a package. A program may contain any number of import statements.

Importing specific class


Using an importing statement, we can import a specific class. The following
syntax isemployed to import a specific class.

Syntax: import packageName.ClassName;

Example for User-defined Package


If we declare a package in source file, the package declaration must be the first
statement in the source file.

Since the package creates a new namespace there won’t be any name conflicts
with names in other packages. Using packages it is easier to provide access
control and it is also locate the related classes.

Example for Add.java file


package mypack;
public class Add
{
int x,y;
public Add()
{
x=10;
y=20;
}
public void sum()
{
System.out.println("Addition of two Numbers :"+(x+y));
}
}

Now save the file Add.java and create new folder for mypack (like D:\TKREC\Java\mypack)
then keep the Add.java source file in mypack folder. Now take the another class to access
this Add() method

Example for Demo.java file


import mypack.Add;
class Demo
{
public static void main(String args[])
{
Add obj=new Add();
obj.sum();
}
}

Now save the file Demo.java in your folder (like D:\TKREC\Java)

Now we need to compile Add.java file then compile and run Demo.java file

P.Ramesh, Assistant Professor,AIML Dept, TKREC 45


OOP through Java UNIT-2

OUTPUT:

D:\TKREC\Java>cd mypack

D:\TKREC\Java\mypack>javac Add.java

D:\TKREC\Java\mypack>cd..

D:\TKREC\Java>javac Demo.java

D:\TKREC\Java>java Demo
Addition of two Numbers: 30

// Example for Built in Package


import java.util.Scanner;
public class ImportingExample
{
public static void main(String args[])
{
// creates an object of Scanner
Scanner sc= new Scanner(System.in);
System.out.print("Enter your name: ");

// takes input from the keyboard


String name=sc.nextLine();

// prints the name


System.out.println("My name is: " + name);

// closes the scanner


sc.close();
}
}
OUTPUT:
D:\Java>java ImportingExample
Enter your name: siri
My name is: siri

Importing all the classes


Using an importing statement, we can import all the classes and interfaces of
a package will be accessible but not the sub packages. To import all the
classes of the package, we use * symbol.

The following syntax is employed to import all the classes of a package.

Syntax: import packageName.*;

P.Ramesh, Assistant Professor,AIML Dept, TKREC 46


OOP through Java UNIT-2
// Example for User-defined Package

Humans.java file
package animals;
class Animals
{
public void display()
{
System.out.println("All the animals are in the World");
}
}
public class Humans extends Animals
{
public void show()
{
System.out.println(" class A animals are Humans");
}
public void msg()
{
System.out.println(" Humans are Animals with Intelligence");
}
}

Example for World.java file


package pack;
import animals.*;
class World
{
public static void main(String[] args)
{
Humans obj=new Humans();
obj.display();
obj.show();
obj.msg();
}
}
OUTPUT:
D:\Java>javac -d . Humans.java

D:\Java>javac -d . World.java

D:\Java>java pack.World
All the animals are in the World
class A animals are Humans
Humans are Animals with Intelligence

// Example for Built in Package


import java.lang.*;
public class PredefinedPackages
{

P.Ramesh, Assistant Professor,AIML Dept, TKREC 47


OOP through Java UNIT-2
public static void main(String[] args)
{
double radius=5.0;
// double area=3.14* radius* radius;
double area=Math.PI * Math.pow(radius, 2);
System.out.println("Area: " + area);

String message="Hello, World!";


int length=message.length();
System.out.println("Length: " + length);

int number=42;
String binary=Integer.toBinaryString(number);
System.out.println("Binary: " + binary);
}
}
OUTPUT:
D:\Java>java PredefinedPackages
Area: 78.53981633974483
Length: 13
Binary: 101010

In the above example, we import java.lang.* to have access to some of the fundamental
classes provided by Java, such as Math, String, and Integer. The code demonstrates the
usage of these classes by calculating the area of a circle, determining the length of a string,
and converting an integer to its binary representation.

The import statement imports only classes of the package, but not sub-packages
and its classes. We may also import sub-packages by using a symbol '.' (dot) to
separate parent package and sub-package.

Note: If you import a package, sub-packages will not be imported. i.e if you
import a package , all the classes and interfaces of that package will be imported
excluding the classes and interfaces of sub packages. Hence you need to import
the sub packages as well.

Rule: There can be only one public class in java source file and it must be
saved by the public class name.

Sub-package
Package inside the package is called sub package. It should be created to categorize the
package further.

The standard of defining package is package name.sub package name.


for example “pack.subpack”.

Example
package pack.subpack;
class SubpackDemo
{

P.Ramesh, Assistant Professor,AIML Dept, TKREC 48


OOP through Java UNIT-2
public static void main(String[] args)
{
System.out.println(" Hello Sub Package ");
}
}
OUTPUT:
D:\Java>javac -d . SubpackDemo.java
D:\Java>java pack.subpack.SubpackDemo
Hello Sub Package

Differences between classes and interfaces


A class in Java is a blueprint from which an object is created. Every Java class must belong to
some packages which are nothing but a group of similar types of classes, interfaces, and sub-
packages bundled together. A class is a logical entity that defines the behavior and
properties of an object. In other words, a class in Java is used to create and define objects,
object data types, and methods

A class declaration generally constitutes of the following parts:


 Modifiers
 Class name
 Keywords
 The class body within curly brackets { }

An interface in Java is one of the reference types defined in Java. It is syntactically similar to
a class but it contains abstract methods. To create an interface the keyword interface is
used. Along with abstract methods, an interface can also include constants, static methods,
nested interfaces and default methods. Any number of classes can implement an interface by
using the implements keyword. An interface an also inherit other interfaces using the extend
keyword.

Class Interface
A class can be instantiated An interface can never be instantiated
The class keyword is used to declare it The interface keyword is used
The members of a class can be declared The members of an interface are always
as private, public or protected declared as public
Contains the concrete methods i.e Contains abstract method i.e methods
methods with body without the body
The extends keyword is used to inherit The implements keyword is used to use
a class Can contain final and static an interface Cannot contain final or static
methods methods
A Java class can have constructors An interface cannot have constructors
A class can extend only one class but An interface can extend any number of
can implement any number of interfaces but cannot implement any
interfaces interface

P.Ramesh, Assistant Professor,AIML Dept, TKREC 49


OOP through Java UNIT-2

Defining an interface in java


In java, an interface is similar to a class, but it contains abstract methods and
static finalvariables only. The interface in Java is another mechanism to achieve
abstraction. We may think of an interface as a completely abstract class.

The interface in java enables to support multiple-inheritance. An interface may


extend only one interface, but a class may implement any number of interfaces.
 An interface is a container of abstract methods and static final variables.
 An interface implemented by a class. (class implements interface).
 An interface may extend another interface. (Interface extends Interface).
 An interface never implements another interface, or class.
 A class may implement any number of interfaces.
 We cannot instantiate an interface.

Specifying the keyword abstract for interface methods is optional, it


automaticallyadded. Defining an interface is similar to that of a class. We use the
keyword interface to define an interface. All the members of an interface are
public by default.

The following is the syntax for defining an interface.

Syntax:
interface InterfaceName
{
members declaration;
}

Example
interface HumanInterfaceExample
{
void learn(String str);
void work();
int duration = 10;
}

In the above code defines an interface HumanInterfaceExample that contains


twoabstract methods learn(), work() and one constant duration.

Every interface in Java is auto-completed by the compiler. For example, in


the above example code, no member is defined as public, but all are public
automatically. The above code automatically converted as follows.

Converted code
interface HumanInterfaceExample
{
public abstract void learn(String str);
public abstract void work();
public static final int duration = 10;
}
P.Ramesh, Assistant Professor,AIML Dept, TKREC 50
OOP through Java UNIT-2

Implementing an Interface in java


In java, an interface is implemented by a class. The class that implements an
interface must provide code for all the methods defined in the interface, otherwise,
it must be defined as an abstract class.

The class uses a keyword implements to implement an interface. A class can


implement any number of interfaces. When a class wants to implement more
than one interface, we use the implements keyword is followed by a comma -
separated list of the interfaces implemented by the class.

Syntax
class className implements InterfaceName
{
boby-of-the-class
}

/* you can access the default methods of an interface using the objects of the
implementing classes.*/

interface MyInterface
{
public static int num = 100;
public default void display()
{
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface
{
public static void main(String args[])
{
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}
OUTPUT:
D:\TKREC\Java>java InterfaceExample
display method of MyInterface

// implementing an Interface in java

Example
interface Human
{
void learn(String str);
void work();
int duration = 10;
}

P.Ramesh, Assistant Professor,AIML Dept, TKREC 51


OOP through Java UNIT-2
class Programmer implements Human
{
public void learn(String str)
{
System.out.println("Learn using " + str);
}
public void work()
{
System.out.println("Develop applications");
}
}
public class SingleInterface
{
public static void main(String[] args)
{
Programmer trainee = new Programmer();
trainee.learn("coding");
trainee.work();
}
}
OUTPUT:
D:\Java>java SingleInterface
Learn using coding
Develop applications

In the above code defines an interface Human that contains two abstract
methods learn(), work() and one constant duration. The class Programmer
implements the interface. As it implementing the Human interface it must provide
the body of all the methods those defined in the Human interface.

Implementing multiple Interfaces


When a class wants to implement more than one interface, we use the
implements keyword is followed by a comma-separated list of the interfaces
implemented by the class.

Syntax:
class className implements InterfaceName1, InterfaceName2
{
boby-of-the-class
}

Example
interface Human
{
void learn(String str);
void work();
}
interface Recruitment
{
boolean screening(int score);

P.Ramesh, Assistant Professor,AIML Dept, TKREC 52


OOP through Java UNIT-2
boolean interview(boolean selected);
}
class Programmer implements Human, Recruitment
{
public void learn(String str)
{
System.out.println("Learn using " + str);
}
public boolean screening(int score)
{
System.out.println("Attend screening test");
int thresold = 20;
if(score > thresold)
return true;
return false;
}
public boolean interview(boolean selected)
{
System.out.println("Attend interview");
if(selected)
return true;
return false;
}
public void work()
{
System.out.println("Develop applications");
}
}
public class MultipleInterface
{
public static void main(String[] args)
{
Programmer trainee = new Programmer();
trainee.learn("Coding");
trainee.screening(30);
trainee.interview(true);
trainee.work();
}
}
OUTPUT:
D:\Java>java MultipleInterface
Learn using Coding
Attend screening test
Attend interview
Develop applications

In the above code defines two interfaces Human and Recruitment, and a
class Programmer implements both the interfaces.

Applying interfaces (OR) Nested Interfaces in java


P.Ramesh, Assistant Professor,AIML Dept, TKREC 53
OOP through Java UNIT-2

In java, an interface may be defined inside another interface, and also inside a
class. The interface that defined inside another interface or a class is known
as nested interface.The nested interface is also referred as inner interface.
 The nested interface declared within an interface is public by default.
 The nested interface declared within a class can be with any access
modifier.
 Every nested interface is static by default.

The nested interface cannot be accessed directly. We can only access the nested
interface by using outer interface or outer class name followed by dot( . ), followed
by the nested interface name.

Nested interface inside another interface


The nested interface that defined inside another interface must be
accessed as OuterInterface.InnerInterface.

Example
interface OuterInterface
{
void outerMethod();
interface InnerInterface
{
void innerMethod();
}
}

class OnlyOuter implements OuterInterface


{
public void outerMethod()
{
System.out.println("This is OuterInterface method");
}
}

class OnlyInner implements OuterInterface.InnerInterface


{
public void innerMethod()
{
System.out.println("This is InnerInterface method");
}
}
public class NestedInterface
{
public static void main(String[] args)
{
OnlyOuter obj1 = new OnlyOuter();
OnlyInner obj2 = new OnlyInner();
obj1.outerMethod();
obj2.innerMethod();

P.Ramesh, Assistant Professor,AIML Dept, TKREC 54


OOP through Java UNIT-2
}
}
OUTPUT:
D:\Java>java NestedInterface
This is OuterInterface method
This is InnerInterface method

Nested interface inside a class


The nested interface that defined inside a class must be accessed as
ClassName.InnerInterface

Example
class OuterClass
{
interface InnerInterface
{
void innerMethod();
}
}

class ImplementingClass implements OuterClass.InnerInterface


{
public void innerMethod()
{
System.out.println("This is InnerInterface method");
}
}

public class NestedInterfaceinclass


{
public static void main(String[] args)
{
ImplementingClass obj = new ImplementingClass();
obj.innerMethod();
}
}
OUTPUT:
D:\Java>java NestedInterfaceinclass
This is InnerInterface method

Variables in Java Interfaces


In java, an interface is a completely abstract class. An interface is a container of
abstract methods and static final variables. The interface contains the static final
variables. The variables defined in an interface cannot be modified by the class
that implements the interface, but it may use as it defined in the interface.
 The variable in an interface is public, static, and final by default.
 If any variable in an interface is defined without public, static, and final
keywordsthen, the compiler automatically adds the same.
 No access modifier is allowed except the public for interface variables.
 Every variable of an interface must be initialized in the interface itself.
P.Ramesh, Assistant Professor,AIML Dept, TKREC 55
OOP through Java UNIT-2
 The class that implements an interface cannot modify the interface
variable, but itmay use as it defined in the interface.

Example
interface SampleInterface
{
int UPPER_LIMIT = 100;
//int LOWER_LIMIT; // Error - must be initialised
}

public class InterfaceVariablesExample implements SampleInterface


{
public static void main(String[] args)
{
System.out.println("UPPER LIMIT = " + UPPER_LIMIT);
// UPPER_LIMIT = 150; // Cannot be modified
}
}
OUTPUT:
D:\TKREC\Java>java InterfaceVariablesExample
UPPER LIMIT = 100

Extending an Interface in java


In java, an interface can extend another interface. When an interface wants to
extend another interface, it uses the keyword extends. The interface that
extends another interface has its own members and all the members defined in
its parent interface too. The class which implements a child interface needs to
provide code for the methods defined in both child and parent interfaces,
otherwise, it needs to be defined as abstract class.
 An interface can extend another interface.
 An interface cannot extend multiple interfaces.
 An interface can implement neither an interface nor a class.
 The class that implements child interface needs to provide code for all the
methodsdefined in both child and parent interfaces.

Example
interface ParentInterface
{
void parentMethod();
}

interface ChildInterface extends ParentInterface


{
void childMethod();
}

class ImplementingClass implements ChildInterface


{
public void childMethod()
{
P.Ramesh, Assistant Professor,AIML Dept, TKREC 56
OOP through Java UNIT-2
System.out.println("Child Interface method!!");
}
public void parentMethod()
{
System.out.println("Parent Interface mehtod!");
}
}

public class ExtendingInterface


{
public static void main(String[] args)
{
ImplementingClass obj = new ImplementingClass();
obj.childMethod(); obj.parentMethod();
}
}
OUTPUT:
D:\TKREC\Java>java ExtendingInterface
Child Interface method!!
Parent Interface mehtod!

Exploring java.io
In java, the IO operations are performed using the concept of streams.
Generally, a stream means a continuous flow of data. In java, a stream is a
logical container of datathat allows us to read from and write to it. A stream
can be linked to a data source, or data destination like a console, file or
network connection by java IO system. The stream- based IO operations are
faster than normal IO operations. The Stream is defined in the java.io package.

In java, the stream-based IO operations are performed using two separate


streams input stream and output stream. The input stream is used for input
operations, and the output stream is used for output operations. The java

P.Ramesh, Assistant Professor,AIML Dept, TKREC 57


OOP through Java UNIT-2
stream is composed of bytes.

In Java, every program creates 3 streams automatically, and these streams are
attachedto the console.
 System.out: standard output stream for console output operations.
 System.in: standard input stream for console input operations.
 System.err: standard error stream for console error output operations.

The Java streams support many different kinds of data, including simple bytes,
primitive data types, localized characters, and objects. Java provides two types of
streams, and they are as follows. The following picture shows how streams are
categorized, and various built-in classes used by the java IO system.
 Byte Stream
 Character Stream
Both character and byte streams essentially provide a convenient and
efficient way tohandle data streams in Java.

Byte Stream in java


In java, the byte stream is an 8 bits carrier. The byte stream in java allows us to
transmit 8 bits of data.
 In Java 1.0 version all IO operations were byte oriented, there was no other
stream (character stream).
 The java byte stream is defined by two abstract classes, InputStream and
OutputStream.
 The InputStream class used for byte stream based input operations, and
the OutputStream class used for byte stream based output operations.
 The InputStream and OutputStream classes have several concreate

P.Ramesh, Assistant Professor,AIML Dept, TKREC 58


OOP through Java UNIT-2
classes to performvarious IO operations based on the byte stream.

The following picture shows the classes used for byte stream operations.

InputStream class: The InputStream class has defined as an abstract class, and
it hasthe following methods which have implemented by its concrete classes.

S.N Method with Description


o.
1 int available()
It returns the number of bytes that can be read from the input stream.

2 int read()
It reads the next byte from the input stream.

3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in
its bytearray, b.

4 void close()
It closes the input stream and also frees any resources connected
with thisinput stream.

OutputStream class: The OutputStream class has defined as an abstract


class, and ithas the following methods which have implemented by its concrete
classes.

S.No Method with Description

P.Ramesh, Assistant Professor,AIML Dept, TKREC 59


OOP through Java UNIT-2
.

1 void write(int n)
It writes byte(contained in an int) to the output stream.

2 void write(byte[] b)
It writes a whole byte array(b) to the output stream.

3 void flush()
It flushes the output steam by forcing out buffered bytes to be written
out.
4 void close()
It closes the output stream and also frees any resources connected
with thisoutput stream.

Reading data using BufferedInputStream: We can use the BufferedInputStream


class to read data from the console. The BufferedInputStream class use a metho
read( ) to read a value from the console, or file, or socket.

Let's look at an example code to illustrate reading data using


BufferedInputStream.

// Java Console readLine(String fmt, Object args) Method

/* The readLine(String fmt, Object args) method is a static method of Java Console class.
It is used to provide a formatted prompt, then reads a single line of text from the console.

Syntax: -

public String readLine( String fmt, Object args) throws IOException

import java.io.Console;

class ReadLineMethod
{
public static void main(String args[])
{
String str;

//Obtaining a reference to the console.


Console con = System.console();

// Checking If there is no console available, then exit.


if(con == null)
{
System.out.print("No console available");
return;
}

// Read a string and then display it.


P.Ramesh, Assistant Professor,AIML Dept, TKREC 60
OOP through Java UNIT-2
str = con.readLine("Enter your name: ");
con.printf("Here is your name: %s\n", str);
}
}
OUTPUT:
D:\TKREC\Java>java ReadLineMethod
Enter your name: siri
Here is your name: siri

// Reading data from keyboard using BufferedInputStream class

/* Buffered Reader reads the characters (or) strings


1. read() :- Reads single character
2. readLine() :- Reads Multiple characters string
*/
import java.io.*;
public class ByteStreamReadingDemoConsole
{
public static void main(String[] args) throws IOException
{
BufferedInputStream obj = new BufferedInputStream(System.in);
System.out.print("Enter any character: ");
char c = (char)obj.read();
System.out.println("You have entered '" + c + "'");
}
}
OUTPUT:
D:\TKREC\Java>java ByteStreamReadingDemoConsole
Enter any character: s
You have entered 's'

// Example: Reading data from a file

/* Buffered Reader reads the characters (or) strings


1. read() :- Reads single character
2. readLine() :- Reads Multiple characters string
*/

import java.io.*;
public class ByteStreamReadingDemoFile
{
public static void main(String[] args) throws IOException
{
FileInputStream f = new FileInputStream(new File("D:\\TKREC\\Java\\datafile.txt"));
BufferedInputStream obj = new BufferedInputStream(f);
char c = (char)obj.read();
System.out.println("Data read from a file - '" + c + "'");
}
}

P.Ramesh, Assistant Professor,AIML Dept, TKREC 61


OOP through Java UNIT-2
OUTPUT:
D:\TKREC\Java>java ByteStreamReadingDemoFile
Data read from a file - 'j'

Writing data using BufferedOutputStream

We can use the BufferedOutputStream class to write data into the console, file,
socket. The BufferedOutputStream class use a method write( ) to write data.

Let's look at an example code to illustrate writing data into a file using
BufferedOutputStream.

// Writing data into a File using BufferedOutputStream in Byte Stream class

import java.io.*;
public class WritingDemoFile
{
public static void main(String[] args) throws IOException
{
String data = "Welcome To TKR College";
BufferedOutputStream out = null;
try {
FileOutputStream fos = new FileOutputStream(new File("C:\\Java\\outputfile.txt"));
out = new BufferedOutputStream(fos);
out.write(data.getBytes());
System.out.println("Writing data into a file is success!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}
OUTPUT:
D:\TKREC\Java>java WritingDemoFile
Writing data into a file is success!

P.Ramesh, Assistant Professor,AIML Dept, TKREC 62


OOP through Java UNIT-2
Character Stream in java
In java, when the IO stream manages 16-bit Unicode characters, it is called a
character stream. The unicode set is basically a type of character set where each
character corresponds to a specific numeric value within the given character set,
and everyprogramming language has a character set.

In java, the character stream is a 16 bits carrier. The character stream in java
allows usto transmit 16 bits of data. The character stream was introduced in
Java 1.1 version.

The java character stream is defined by two abstract classes, Reader and Writer.
 The Reader class used for character stream-based input operations.
 The Writer class used for character stream-based output operations.
 The Reader and Writer classes have several concrete classes to perform
various IO operations based on the character stream.

The following picture shows the classes used for character stream operations.

Reader class: The Reader class has defined as an abstract class, and it has the
following methods which have implemented by its concrete classes.

S.N Method with Description


o.
1 int read(): It reads the next character from the input stream.

2 int read(char[] cbuffer): It reads a chunk of characters from the input


streamand stores them in its byte array, cbuffer.

P.Ramesh, Assistant Professor,AIML Dept, TKREC 63


OOP through Java UNIT-2
3 int read(char[] cbuf, int off, int len): It reads characters into a portion
of anarray.

4 int read(CharBuffer target): It reads characters into into the specified


characterbuffer.

5 String readLine(): It reads a line of text. A line is considered to be


terminated byany one of a line feed ('\n'), a carriage return ('\r'), or a
carriage return followed immediately by a linefeed.

6 boolean ready(): It tells whether the stream is ready to be read.

7 void close(): It closes the input stream and also frees any resources
connectedwith this input stream.

Writer class: The Writer class has defined as an abstract class, and it has the
followingmethods which have implemented by its concrete classes.

S.No. Method with Description

1 void flush(): It flushes the output steam by forcing out buffered bytes to
bewritten out.

2 void write(char[] cbuf): It writes a whole array(cbuf) to the output


stream.
3 void write(char[] cbuf, int off, int len)
It writes a portion of an array of characters.

4 void write(int c): It writes single character.

5 void write(String str): It writes a string.

6 void write(String str, int off, int len): It writes a portion of a string.

7 Writer append(char c): It appends the specified character to the writer.

8 Writer append(CharSequence csq)


It appends the specified character sequence to the writer

9 Writer append(CharSequence csq, int start, int end)


It appends a subsequence of the specified character sequence to the
writer.
10 void close(): It closes the output stream and also frees any resources
connectedwith this output stream.

Let's look at an example code to illustrate reading data using BufferedReader.


Character Stream in java
The java character stream is defined by two abstract classes, Reader and Writer. The

P.Ramesh, Assistant Professor,AIML Dept, TKREC 64


OOP through Java UNIT-2
Reader class used for character stream-based input operations, and the Writer class used for
character stream-based output operations.

Reading data using BufferedReader


We can use the BufferedReader class to read data from the console. The
BufferedInputStream class needs InputStreamReaderclass. The BufferedReader use a
method read( ) to read a value from the console, or file, or socket.

// Reading data from Console using BufferedReader in Character Stream class.


import java.io.*;
public class CharReadingDemoConsole
{
public static void main(String[] args) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String name = "";
System.out.print("Please enter your name: ");
name = in.readLine();
System.out.println("Hello, " + name + "!");
}
}

OUTPUT:
C:\Java>javac CharReadingDemoConsole.java
C:\Java>java CharReadingDemoConsole
Please enter your name: siri
Hello, siri!

// Reading data from File using BufferedReader in Character Stream class.

import java.io.*;
public class CharReadingDemoFile
{
public static void main(String[] args) throws IOException
{
Reader in = new FileReader("C:\\Java\\datafile1.txt");
try {
char c = (char)in.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
in.close();
}
}
}

P.Ramesh, Assistant Professor,AIML Dept, TKREC 65


OOP through Java UNIT-2
// text file:datafile.txt
Hello Students How are u

OUTPUT:
C:\Java>javac CharReadingDemoFile.java
C:\Java>java CharReadingDemoFile
Data read from a file - 'H'

Writing data using FileWriter


We can use the FileWriter class to write data into the file. The FileWriter class use a method
write( ) to write data.

// Writing data into a File using FileWriter in Character Stream class

import java.io.*;
public class CharWritingDemoFile
{
public static void main(String[] args) throws IOException
{
Writer out = new FileWriter("C:\\Java\\datafile2.txt");
String msg = "Welcome Students";
try {
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}
OUTPUT:
C:\Java>javac CharWritingDemoFile.java
C:\Java>java CharWritingDemoFile
Writing done!!!

P.Ramesh, Assistant Professor,AIML Dept, TKREC 66

You might also like