0% found this document useful (0 votes)
403 views75 pages

Unit 2 Java Notes

The document discusses inheritance in Java including hierarchical abstractions, forms of inheritance like specialization and construction, benefits like code reusability, and costs. It covers member access rules, using the super keyword, polymorphism through method overriding, abstract classes, packages, interfaces, and extending interfaces. Key concepts covered include inheritance basics, types of inheritance like single, multilevel, and hierarchical, using the super keyword to access variables and methods from the parent class, and creating a multilevel class hierarchy as an example.

Uploaded by

198r1a0420
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)
403 views75 pages

Unit 2 Java Notes

The document discusses inheritance in Java including hierarchical abstractions, forms of inheritance like specialization and construction, benefits like code reusability, and costs. It covers member access rules, using the super keyword, polymorphism through method overriding, abstract classes, packages, interfaces, and extending interfaces. Key concepts covered include inheritance basics, types of inheritance like single, multilevel, and hierarchical, using the super keyword to access variables and methods from the parent class, and creating a multilevel class hierarchy as an example.

Uploaded by

198r1a0420
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/ 75

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.

1
UNIT-2

1. Inherirance Concept

Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new
class is known as subclass. The subclass inherits all of its instances variables and methods defined by the
superclass and it also adds its own unique elements. Thus we can say that subclass are specialized version of
superclass.

Benefits of Java’s Inheritance

1. Reusability of code
2. Code Sharing
3. Consistency in using an interface

1. Inherirance Basics

Defination:The process by which one class acquires the properties(data members) and functionalities
(methods) of another class is called inheritance.

The aim of inheritance is to provide the reusability of code so that a class has to write only the unique
features and rest of the common properties and functionalities can be extended from the another class.

Child Class:

The class that extends the features of another class is known as child class, sub class or derived class.

Parent Class:

The class whose properties and functionalities are used(inherited) by another class is known as parent class,
super class or Base class.

• Inheritance is a process of defining a new class based on an existing class by extending its common
data members and methods.
• Inheritance allows us to reuse of code, it improves reusability in your java application.
Note: The biggest advantage of Inheritance is that the code that is already present in base class

2
need not be rewritten in the child class.This means that the data members(instance variables) and
methods of the parent class can be used in the child class as.

Syntax: Inheritance in Java

To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is parent
class. The class XYZ is inheriting the properties and methods of ABC class.

class XYZ extends ABC

Types of inheritance

1. Single Inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple Inheritance

1.Single Inheritance: refers to a child and parent class relationship where a class extends the another class.

2.Multilevel inheritance: refers to a child and parent class relationship where a class extends the child
class. For example class C extends class B and class B extends class A.

3
3.Hierarchical inheritance: refers to a child and parent class relationship where more than one classes extends
the same class. For example, classes B, C & D extends the same class A.

4.Multiple Inheritance: refers to the concept of one class extending more than one classes, which means a
child class has two parent classes. For example class C extends both classes A and B. Java doesn’t support
multiple inheritance.

5.Hybrid inheritance: Combination of more than one types of inheritance in a single program. For example
class A & B extends class C and another class D extends class A then this is a hybrid inheritance example
because it is a combination of single and hierarchical inheritance.

4
1. Member Access

Member Access and Inheritance

An instance variable of a class will be declared private to prevent its unauthorized use or tampering.
Inheriting a class does not overrule the private access restriction. Thus, even though a subclass includes all
of the members of its superclass, it cannot access those members of the superclass that have been
declared private. For example, if, as shown here, width and height are made private in TwoDShape,
then Triangle will not be able to access them:

5
The Triangle class will not compile because the reference to width and height inside the area( ) method
causes an access violation. ...

Java-Superclass Variable Can Reference a Subclass Object


Superclass Variable Can Reference a Subclass Object
A reference variable of a superclass can be assigned a reference to any subclass derived from that superclass.
In the following program, obj is a reference to NewData object, Since NewData is a subclass of Data, it is
permissible to assign obj a reference to the NewData object. When a reference to a subclass object is
assigned to a superclass reference variable, you will have access only to those parts of the object defined by
the superclass. This is way obj can’t access data3 and data4 even it refers to a NewData object.
Program

6
1. Creating Multilevel Hierarchy

Create multilevel hierarchy

It is nothing but the enhancement of the Simple Inheritance. From the type name, it is pretty much clear that
Inheritance is done at ‘n’ number of levels, where n>1.
In simple inheritance, a subclass or derived class derives the properties from its parent class, but in
multilevel inheritance, a subclass is derived from a derived class. One class inherits the only single class.
Therefore, in multilevel inheritance, every time ladder increases by one. The lowermost class will have the
properties of all the superclass.

7
class A{
public A()
{
System.out.println("class A constructor");
}
public void hai()
{
System.out.println("hai method");
}
}
class B extends A{
public B()
{
System.out.println("class B constructor ");
}
public void hello()
{
System.out.println("hello method");
}
public void welcome()
{
System.out.println("class B welcome");
}
}
public class C extends B
{

public C()
{
System.out.println("class C constructor");
}
public void welcome()
{
System.out.println("class C welcome");
}
public static void main(String args[])
Output: {
C obj=new C();
obj.hai();
class A constructor obj.hello();
obj.welcome();
class B constructor }
}
class C constructor

hai method

hello method

8
class C welcome

Note: Multilevel inheritance is not multiple inheritances where one class can inherit more than one class at a
time. Java does not support multiple inheritances.

1. Super Uses

super keyword in java

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

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable

Usage of java super Keyword

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


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.The use of super keyword

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if parent class and
child class have same fields.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if subclass contains the
same method as parent class. In other words, it is used if method is overridden.

Example program to demonstrating invoking of parent class instance variable and parent class method

9
class Base
{
String color="white";
void display()
{
System.out.println("have a nice day");
}
}
Class Sub extends Base
{
String color="black";
void display()
{
System.out.println("Hello CMREC...");
}
void printColor()
{
System.out.println(color);//prints color of sub class
System.out.println(super.color);//prints color of Base class
}

void work()
{
display();
super.display();

}
}
class TestSuper2
{
public static void main(String args[])
{
Sub ob=new Sub();
ob. printColor();
ob.work();
}
}

Output

black

10
white

Hello CMREC…

have a nice day

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor.

class Parentclass
{
Parentclass()
{
System.out.println("Constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass()
{
//Compile implicitly adds super() here as the first statement of this
constructor.
System.out.println("Constructor of child class");
}
Subclass(int num)
{
// Even though it is a parameterized constructor The compiler still adds the super() here
System.out.println("arg constructor of child class");
}
void display()
{
System.out.println("Hello!");
}
public static void main(String args[])
{
Subclass obj= new Subclass();
//Calling sub class method
obj.display();
Subclass obj2= new Subclass(10);
obj2.display();
}
}

11
Output:
Constructor of parent class
Constructor of child class
Hello!
Constructor of parent class
arg constructor of child class
Hello!

1. Using Final with Inheritance


.
Final Keyword In Java

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

if a variable is made as final it cannot change its value

if a method is made as final it cannot override it.

If a class is made as final it cannot be extended by another class

Program to demonstrate using final with inheritance

final class Bike


{

class Honda1 extends Bike //error since Bike is final we can’t inherit it properties
{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[]){


Honda1 honda= new Honda();
honda.run();
}
}

12
1. Polymorphism-ad hoc polymorphism

Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java:

1. Compile-time polymorphism or Ad hoc polymorphism


2. Runtime polymorphism. Or Pure polymorphism

We can perform polymorphism in java by method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time polyymorphism.

13
1. Compile-time polymorphism or Ad hoc polymorphism:

Ad hoc polymorphism is also known as function overloading or operator overloading because a


polymorphic function can represent a number of unique and potentially different implementations
depending on the type of argument it is applied to.

The term ad hoc in this context is not intended to be pejorative; it refers simply to the fact that this type of
polymorphism is not a fundamental feature of the type system.

i)operator overloading:

Java also provide option to overload operators. For example, we can make the operator (‘+’) for string class
to concatenate two strings. We know that this is the addition operator whose task is to add two operands. So
a single operator ‘+’ when placed between integer operands, adds them and when placed between string
operands, concatenates them.

In java, Only “+” operator can be overloaded:

Example on Operator overloading

// Java program for Operator overloading

class Operatoroverloading {

void operator(String str1, String str2)


{
String s = str1 + str2;
System.out.println("Concatinated String - "+ s);
}

void operator(int a, int b)


{
int c = a + b;
System.out.println("Sum = " + c);
}
}

class Main {
public static void main(String[] args)
{
Operatoroverloading obj = new Operatoroverloading ();
obj.operator(2, 3);
obj.operator("CMR", "EC");
}
}

14
Output:

Sum = 5

Concatinated String -CMREC

ii)Method Overloading:

When there are multiple functions with same name but different parameters then these functions are said to
be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of
arguments. Overloaded methods are generally used when they conceptually execute the same task but with a
slightly different set of parameters.

Example on method overloading


class MultiplyFun {
// Java program for Method overloading
// Method with 2 parameter
static int Multiply(int a, int b)
Output:
{
8
return a * b;
16 }
34.65 // Method with 3 parameter
static int Multiply(int a, int b,int c)
Note: {
we overload static methods return a * b*c;
we cannot overload methods that differ only by static}keyword
we overload main() in Java

// Method with the same name but 2 double parameter


static double Multiply(double a, double b)
{
return a * b;
}
}

2. Runtime polymorphism. Or Pure polymorphism


class Main {
public static void main(String[] args)
Runtime polymorphism or Dynamic Method Dispatch
{ is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.
System.out.println(MultiplyFun.Multiply(2,
In this process, an overridden method is called4)); through the reference variable of a superclass. The
determination of the method to be called is based on the objectSystem.out.println(MultiplyFun.Multiply(2,
being referred to by the reference variable.
4,2));
System.out.println(MultiplyFun.Multiply(5.5,
Let's first understand the upcasting before Runtime Polymorphism.
6.3));
Upcasting }
}
15
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.

For example:

class A{}

class B extends A{}

A a=new B();//upcasting .

Example of Java Runtime Polymorphism

In this example, we are creating two classes A and B. B class extends A class and overrides its
display ()method. We are calling the display ()by the reference variable of Parent class. Since it refers to the
subclass object and subclass method overrides the Parent class method, the subclass method is invoked at
runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

class A
{
void display ()
{
System.out.println(" A class display ");
}
}
class B extends A
{
void display ()
{
System.out.println(" B class display ");
}
public static void main(String args[])
{
A obj = new B();//upcasting
obj. display ();
}
}

16
Output:

B class display

Advantages of dynamic binding along with polymorphism with method overriding are.

o Less memory space


o Less execution time
o More performance

Difference between Static & Dynamic Polymorphism

Static Polymorphism Dynamic Polymorphism

Compile time polymorphism or static


Run time polymorphism or dynamic polymorphism or
1 polymorphism relates to method
dynamic binding relates to method overriding.
overloading.
Difference between Method overloading and Method overriding
Method overloading Method overriding

1 When a class have same method name with Method overriding - Method of superclass is
different argument, than it is called method overridden in subclass to provide more specific
overloading. implementation.

2 Method overloading is generally done in Method overriding is always done in subClass in java.
same class but can also be done in
SubClass .

3 Both Static and instance method can be Only instance methods can be overridden in java.
overloaded in java. Static methods can’t be overridden in java.

4 Main method can also be overloaded in Main method can’t be overridden in java, because
java main is static method and static methods can’t be
overridden in java (as mentioned in above point)

5 private methods can be overloaded in java. private methods can’t be overridden in java, because
private methods are not inherited in subClass in java.

6 final methods can be overloaded in java. final methods can’t be overridden in java, because
final methods are not inherited in subClass in java.

7 Call to overloaded method is bonded at Call to overridden method is bonded at runtime in


compile time in java. java.

8 Method overloading concept is also known Method overriding concept is also known as runtime
as compile time polymorphism or ad hoc time polymorphism or pure polymorphism or
polymorphism or static binding in java. Dynamic binding in java.
17
1. Method Overriding

In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.variable of the current object.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting

class A{} class A


{
class B extends A{} void display ()
{
A a=new B();//upcasting System.out.println(" A class display ");
}
. Output: }
class B extends A
B class display
{
void display ()
{
System.out.println(" B class display ");
}
public static void main(String args[])
{
A obj = new B();//upcasting
obj. display ();
}
}

1. Abstract Classes

Abstract class in Java

• A class that is declared with abstract keyword, is known as abstract class in java.
• It can have abstract and non-abstract methods (method with body).
• It needs to be extended and its method implemented.
18
• It cannot be instantiated.

Example abstract class

abstract class A

Abstract method

A method that is declared as abstract and does not have implementation is known as abstract method.

Example abstract method

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

Example on abstract class and method

abstract class Hello


{
abstract void hai();
}
abstract class Demo extends Hello
{
}
class Welcome extends Demo
{
void hai()
{
System.out.println("hello");
}
}
public class AbstractClass {
public static void main(String args[])
{
//A oa=new A();//error because for abstract class we can't create object
//Demo ob=new Demo();//error because for abstract class we can't create object
//ob.hai();//error
Welcome oh=new Welcome();
oh.hai();
}
}

19
Output:hello

Abstract class Interface


1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8,
abstract methods. it can have default and static methods also.
2) Abstract class doesn't support multiple
Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, static
Interface has only static and final variables.
and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare
The interface keyword is used to declare interface.
abstract class.
6)Example: Example:
public Abstract Class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

1.
Object Class

There is one special class, Object, defined by Java.

The Object class is the parent class of all the classes in java by default.

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.

The parent class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object. For example:

Object obj=getObject();//we don't know what object will be returned from this method

20
Methods of Object class

The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() returns the Class class object of this object. The Class
class can further be used to get the metadata of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.

public final void wait(long timeout)throws causes the current thread to wait for the specified
InterruptedException milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).

public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).

public final void wait()throws causes the current thread to wait, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).

protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.

The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. So we cannot override this
methods and rest of the methods can be overridden.

21
1. Forms of Inheritance-Specialization

Forms of Inheritance :

All objects eventually inherit from Object, which provides useful methods such as equals and toString.

In general we want to satisfy substitutability: if B is a subclass of A, anywhere we expect an instance of


A we can use an instance of B.

Inheritance gets used for a number of purposes in typical object-oriented programming:

Specification inheritance:

If the parent class is abstract, we often say that it is providing a specification for the child class, and
therefore it is specification inheritance (a variety of specialization inheritance).

Specialization inheritance:

The superclass just specifies which methods should be available but doesn't give code.

This is supported in java by interfaces and abstract methods

Construction inheritance

The superclass just specifies which methods should be available but doesn't give code.

This is supported in java by interfaces and abstract methods

Extension inheritance

The superclass is just used to provide behavior, but instances of the subclass don't really act like the
superclass. Violates substitutability. Exmample: defining Stack as a subclass of Vector. This is not clean --
better to define Stack as having a field that holds a vector

If a child class generalizes or extends the parent class by providing more functionality, but does not override
any method, we call it inheritance for generalization.

The child class doesn't change anything inherited from the parent, it simply adds new features.

An example is Java Properties inheriting form Hashtable. subclass adds new methods, and perhaps redefines
inherited ones as well

22
Inheritance for Limitation

• If a child class overrides a method inherited from the parent in a way that makes it unusable (for
example, issues an error message), then we call it inheritance for limitation.

• For example, you have an existing List data type that allows items to be inserted at either end, and
you override methods allowing insertion at one end in order to create a Stack.

• Generally not a good idea, since it breaks the idea of substitution. But again, it is sometimes found in
practice. the subclass restricts the inherited behavior. Violates substitutability. Example: defining Queue as a
subclass of Dequeue.

Combination

The child class inherits features from more than one parent class. This is multiple inheritance .

Summary of Forms of Inheritance

Specialization. The child class is a special case of the parent class; in other words, the child class is a
subtype of the parent class.

Specification. The parent class defines behavior that is implemented in the child class but not in the parent
class.

Construction. The child class makes use of the behavior provided by the parent class, but is not a subtype
of the parent class.

Generalization. The child class modifies or overrides some of the methods of the parent class.

Extension. The child class adds new functionality to the parent class, but does not change any inherited
behavior.

Limitation. The child class restricts the use of some of the behavior inherited from the parent class.

Variance. The child class and parent class are variants of each other, and the class-subclass relationship is
arbitrary.

Combination. The child class inherits features from more than one parent class. This is multiple inheritance
.

23
1. Benefits of Inheritance

Benefit of using inheritance:

➢ A code can be used again and again


➢ Inheritance in Java enhances the properties of the class, which means that property of the
parent class will automatically be inherited by the base class
➢ It can define more specialized classes by adding new details.
➢ In addition we have benefits such as

• Software Reuse
• Code Sharing
• Improved Reliability
• Consistency of Interface
• Rapid Prototyping
• Polymorphism
• Information Hiding

1. Cost of Inheritance

➢ Execution speed
➢ Program size
➢ Message Passing Overhead
➢ Program Complexity

This does not mean you should not use inheritance, but rather than you must understand the benefits, and
weigh the benefits against the costs.

24
2.1 Packages

2.1.1 Introduction to packages

A java package is a group of similar types of classes, interfaces and sub-

packages. Package in java can be categorized in two form,

i) built-in package and


ii) user-defined package.

Built-in package:

Collection of classes & interfaces which are already defined are called as Build-in

packages. There are many built-in packages such as java, lang, awt, javax, swing,

net, io, util, sql etc.

user-defined packages:

The collection of classes and interfaces for which definition is


provided by the developer or programmer are called as user-defined
packages.

25
2.1.2 Defining a user-defined package

To create a user defined package in java we use a keyword

“package” Syntax:

package packagename[.subpackage1][.subpackage2]…[.subpackageN];

Sample program on userdefined package:

//save as Simple.java

package mypack;

public class Simple

public static void main(String args[])

System.out.println("Welcome to package");

compile java package:

If you are not using any IDE, you need to follow the syntax given below:

Syntax:

javac -d directory javafilename

For example

26
1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows)
etc. If you want to keep the package within the same directory, you can use . (dot).

run java package program:

You need to use fully qualified name e.g. mypack.Simple etc to run the

class. To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

2.1.3 CLASSPATH Setting

CLASS PATH environment variable setting is used by java run time system to know
where to look for package that is created.

For example, consider the following package specification:

package MyPack

the class path must not include MyPack, itself.

27
It must simply specify the path to MyPack. For example, in a Windows environment,
if the path to MyPack is
C:\MyPrograms\Java\MyPack
Then the class path to
MyPack is
C:\MyPrograms\Java

Example:
package
MyPack; class
Demo

{
…….
…….
}
class classpathdemo
{
public static void main(String args[])
{
Demo obj=new Demo();
………
}

Call this file classpathdemo.java and put it in a directory called MyPack.

Next, compile the file. Make sure that the resulting .class file is also in the MyPack directory.

Then, try executing the classpathdemo class, using the following command line:

java MyPack.classpathdemo

Remember, you will need to be in the directory above MyPack when you execute this
command.

28
2.1.4 Importing packages

There are three ways to access the package from outside the package.

1. import package.*;

2. import package.classname;

3. fully qualified name.

1) Using packagename.*

• If you use package.* then all the classes and interfaces of this package will
be accessible but not subpackages.
• The import keyword is used to make the classes and interface of another
package accessible to the current package.

Example of package that import the packagename.*

//let us save this program in D:/pack folder as A.java

package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

28
Compile as: D:/pack>javac –d . A.java

//save it D floder as B.java

import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}

Compile as: D:\>javac B.java

Run as :D:\> java B

Output:Hello

2) Using packagename.classname

• If you import package.classname then only declared class of this package


will be accessible.
Example of package by import package.classname

package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

Output:Hello
3) Using fully qualified name

• If you use fully qualified name then only declared class of this package will
be accessible. Now there is no need to import. But you need to use fully
qualified name every time when you are accessing the class or interface.
• It is generally used when two packages have same class name e.g. java.util
and java.sql packages contain Date class.

Example of package by import fully qualified name

package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully
qualified name
obj.msg();
}
}
Output:Hello

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages. Hence, you need
to import the subpackage as well.

Implicit and Explicit import statement

Imports can be categorized as explicit (for example import java.util.List;) or implicit


(also known as 'on-demand', for example import java.util.*;):

Implicit imports give access to all visible types in the type (or package) that
precedes the ".*"; types imported in this way never shadow other types.

Explicit imports give access to just the named type; they can shadow other types
that would normally be visible through an implicit import, or through the normal
package visibility rules.

Example

The following example uses implicit imports. This means that it is not clear to a
programmer where the List type on line 5 is imported from.

import java.util.*; // AVOID: Implicit import statements


import java.awt.*;

public class Customers {


public List getCustomers() { // Compiler error: 'List' is ambiguous.
...
}
}
To improve readability, the implicit imports should be replaced by explicit imports.
For example, import java.util.*; should be replaced by import java.util.List; on line 1.

10
2.1.5 Access protection or Access Modifiers

There are two types of modifiers in java: access modifier and non-access modifier. The access
modifiers specifies accessibility (scope) of a datamember, method, constructor or class.

There are 4 types of access modifiers:

1. private

2. default

3. protected

4. public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc.

1) private access modifier:


The private datamembers, method ,contructor are accessible only within class in which their are declared
and out of the class the doesn’t have scope.
Example of private access modifier:

In this example, we have created two classes ‘A’ and ‘Simple’. ‘A’ class contains private data member and
private method. We are accessing these private members from outside the class, so there is compile time
error.
class A
{
private int
data=40; private
void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile
1 Time
1
Error obj.msg();//Compile Time Error

}
Role of Private Constructor:

If you make any class constructor private, you cannot create the instance of that class from outside the
class. For example:

class A
{
private A( )
{
}//private constructor
void msg( )
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A( );//Compile Time Error
}
}

Note: A class cannot be private or protected except nested class


2) default access modifier:
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package.
Example of default access modifier:

In this example, We are accessing the A class from outside its package, since A class is not public, so it
cannot be accessed from outside the package.

1
2
//save by A.java

package pack;
class A
{
void msg( )
{
System.out.println("Hello");
}
}

//save by B.java

import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.

3) protected access modifier:


The protected access modifier is accessible within package and outside the package but
through inheritance only.

1
3
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

Example of protected access modifier

In this example, we have created the two packages “pack” and “ mypack”. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package is declared
as protected, so it can be accessed from outside the class only through inheritance.

package pack;
public class A

protected
{ void System.out.println("Hello");
msg()
}
}

import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}

Output:Hello

1
4
4) public access modifier:
The public access modifier is accessible
everywhere. It has the widest scope among all
other modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

//save by B.java

package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

1
5
Output:Hello

ACCESS MODIFIER PUBLIC PROTECTED PRIVATE


Same class YES YES YES
Subclass in same YES YES NO
package
Other classes in same YES YES NO
package
Subclass in other YES YES NO
packages
Non subclasses in YES NO NO
other packages

2.2 INTERFACES

2.2.1 Introduction to Interfaces

Question: How multiple inheritance is achieved in java?

(or)

Explain about interface concept?

(or)

How a Is-A relationship is possible in java

An interface in java is a blueprint of a class. It has static final constants and abstract methods.

o The interface in java is a mechanism to achieve abstraction.


o There can be only abstract methods in the java interface not method body.
o It is used to achieve abstraction and multiple inheritance in Java.
o Java Interface also represents IS-A relationship.
o It cannot be instantiated just like abstract class.

They are mainly three reasons to use interface. They are given below.

• It is used to achieve abstraction.


• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.

1
6
2.2.2 Defining an Interface

Syntax:
public interface NameOfInterface

// Any number of final, static fields

// Any number of abstract method declarations\

In other words, Interface fields are public, static }and final by default, and methods are public and abstract.

2.2.3 Implementation of Interface

Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another interface but a
class implements an interface

1
7
Example on class implementing interface

interface MyInterface
{
public void method();
}
class Demo implements MyInterface
{
public void method()
{
System.out.println("Implementation of method");
}
public static void main(String arg[])
{

Demo obj=new Demo();


obj. method();
}
}

Output: Implementation of method

1
8
Multiple inheritance is not supported through class in java but it is possible by interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class
because of ambiguity. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class.

For example:
interface Printable
{
void print();
}
interface Showable
{
void show();
}

class TestInterface implements Printable, Showable


{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
TestInterface obj = new TestInterface ();
obj.print();
obj.show();
}
}

Output:
Hello

Welcome
1
9
Difference between abstract class and interface

• Abstract class and interface both are used to achieve abstraction where we can declare the

abstract methods.

• Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface


1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8, it can
abstract methods. have default and static methods also.
2) Abstract class doesn't support multiple
Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final,
Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of abstract
implementation of interface. class.
5) The abstract keyword is used to declare
The interface keyword is used to declare interface.
abstract class.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

2
0
2.2.4 Nested Interfaces

• An interface which is declared within another interface or class is known as nested interface.
• The nested interfaces are used to group related interfaces so that they can be easy to maintain.
• The nested interface must be referred by the outer interface or class.
• It can't be accessed directly.

Points to remember for nested interfaces

• Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.

• Nested interfaces are declared static implicitely.

Syntax of nested interface which is declared within the interface:

interface interface_name

...

public interface nested_interface_name

...

2
1
-Example of nested interface which is declared within the interface

interface Outerinterface

void show();

public interface innerinterface

public void message();

class Test implements Outerinterface.innerinterface

void show()

System.out.println(" implementation of outerinterface show method");

public void message()

System.out.println("implementation of nestedinterface message method");

public static void main(String args[])

Test obj=new

Test();

obj.show();

obj.message();
}
2
2
}

Output:

implementation of outerinterface show method


implementation of nestedinterface message
method.

Syntax of nested interface which is declared within the class


class class_name

...

interface nested_interface_name

...

}
class A
{
public interface innerinterface
{
public void message();
}
}
class NestedTest implements A.innerinterface
{
public void message()
{
System.out.println("implementation of nestedinterface message method");
}
public static void main(String args[])
{
NestedTest obj=new NestedITest();
obj.message();
}
}

Example of nested interface which is declared within the class

2
3
Output:

implementation of nestedinterface message method

Example2:

If class have any members and methods ,then to access this members and methods
• First extend the class and implement the interfaces
So that you will have access to members and methods of class also.

class A
{
void show()
{
System.out.println("Hello");
}
public interface innerinterface
{
public void message();
}
}
class NestedTest extends A implements A.innerinterface
{
public void message()
{
System.out.println("implementation of nestedinterface message method");
}
public static void main(String args[])
{
NestedTest obj=new NestedTest();
obj.show();
obj.message();
}
}

Output:

Hello

implementation of nestedinterface message method");


2
4
NOTE:

If we define a class inside the interface, java compiler creates a static nested class. Let's see how can we
define a class within the interface:

interface interface_name
{
class class_name
{
…..
}
}

2.2.5 Applying Interfaces

A sample example on Applying of interface

interface MyInterface
{
public void method();
}
class Demo implements MyInterface
{
public void method()
{
System.out.println("Implementation of method");
}
public static void main(String arg[])
{
Demo obj=new Demo();
obj. method();
}
}

Output: Implementation of method

2
5
2.2.6 Variables in Interface

• An interface can also contain variables just as classes but the variable in interface must be of
• Public,static and final access modifiers.
• If the variable are not specified with access specifier then during compilation process compiler will
provide this access specifier.

Syntax for declaring variables in interface:

interface interface_name

public static final datatype variablename=value;

….

}
Example for declaring a variable in interface:

interface hai
{
public static final min=5;
}
class demo impliments hai
{
public static void main(string args[])
{
demo obj=new demo();
System.out.println (“minimum value
is”); System.out.println (obj.min);
}
}

2
6
2.2.7 Extension of Interface

Example on interface extending interface:

Interface inheritance

A class implements interface but one interface extends another interface .


interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class TestInterface implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
TestInterface obj = new TestInterface();
obj.print();
obj.show();
}
}

Output:

Hello

Welcome

2
7
2.3 STREAM BASED INPUT/OUTPUT

• A stream in java is a path along which data flows.


• A stream presents a uniform, easy-to-use, object-oriented interface between the program and the
input/output devices
• It has a source (of data) and destination (for that data). Both the source and destination may be
physical devices or programs or other streams in the same program.

OutputStream: Java application uses an output stream to write data to a destination, it may be a file,an
array, peripheral device or socket.

InputStream:Java application uses an input stream to read data from a source, it may be a
file,an array,peripheral device or socket.

2
8
2.3.1 Stream Class
• Java’s Stream based input/output is built upon 4 abstract classes
1. InputStream
2. OutputStream
3. Reader
4. Writer

• InputStreams and OutputStreams are designed for Byte Streams.


• Reader and Writer are designed for Character Streams

2.3.2 Byte Streams- InputStream class and OutputStream class

Byte stream classes have been designed to provide functional features for creating and manipulating
streams and files for reading and writing Bytes.

Java provides two Byte streams

1. InputStream class
2. OutputStream class

1. InputStream Class:

• It is an abstract class that defines model of streaming byte input.


• It implements Closeable interface.
• It defines methods for perfoming input functions such as

➢ Reading Bytes
➢ Closing streams
➢ Marking positions in streams
➢ Skipping ahead in stream
➢ Finding the number of Bytes in a streams

2
9
Below table gives the methods provided by InputStream class

Method Description
int read() Reads a byte form the input stream.and return -1
when end of the file is encountered

int read(byte buffer[ ]) Reads an array of bytes into buffer and return - 1
when end of the file is encountered

int read(byte buffer[ ],int offset , int numbytes) Reads numbytes bytes into buffer starting from
offset.
return -1 when end of the file is encountered

int available() Returns number of bytes available for reading

int skip(long n) Skips over n bytes form the input stream


void reset( ) Goes back to the begining of the stream
void close( ) Close the input stream

2. OutputStream class:

• It is an abstract class that defines model of streaming byte output.


• It implements Closeable and Flushable interface.
• It defines methods for perfoming output functions such as

➢ Writing bytes
➢ Closing streams
➢ Flushing streams

3
0
Below table gives the methods provided by OutputStream class

Method Description
void write(int b) Write a byte to the output stream
void write(byte buffer[]) Write all bytes in the buffer array to the output
stream
write(byte buffer[ ],int offset , int numbytes) Writes numbtes from buffer starting from
offset
void close() Close the output stram
void flush() Flushes the output stream

2.3.3 Character Streams-Reader and Writer Stream class

• The character stream can be used to read and write Unicode characters.
• There are two kinds of character stream classes,namely

1.Reader
2.Writer

1. Reader Stream class:


• It is an abstract class that defines model of streaming character input.
• It implements Closeable and Readable interfaces

Below table gives the methods provided by Reader class

Method Description
abstract void close() Closes the input source
int read() Reads the character from the invoking input stream .
return -1 when end of the file is encountered
int read(char buffer[ ]) Reads an array of character into buffer and return -1
when end of the file is encountered
int read(char buffer[ ],int offset , int Reads numchar bytes into buffer starting from offset.

3
1
numchar) return -1 when end of the file is encountered
boolean ready() Returns true if the next input request will not wait
.otherwise it returns false
void mark(int numChars) Places a mark at the current point in the input stram that
will remain valid until numchars characters are read
void reset() Resets the input pointer to the previously set mark

2. Writer Stream class:

• It is an abstract class that defines model of streaming character output.


• It implements Closeable,Flushable and Appendable interfaces

Below table gives the methods provided by Writer class

Method Description
abstract void close() Closes the output stream.
abstract void flush() Flushes the output stream
Writer append(char ch) Appends ch to the end of output stream
Writer append(CharSequence chars) Appends the chars to the end of the output stream
Writer append(CharSequence chars,int begin,int end) Appends the subrange of chars specified by begin and
end-1 to the output stream.
void write(int ch) Write a single character to the output stream
void write(char buffer[]) Writes the complete array of characters to the output
stream
void write(String str) Write a string str to the output stream
abstract void write(char buffer[],int offset,int Write the subrange of numchars characters from
numChars) buffer beging of the offset to output stream

3
2
2.3.4 Reading Console Input And Writing Console Output
• Reading data from the console input(keyboard)
• There are many ways to read data from the console input keyboard. For example:
• InputStreamReader
• Console
• Scanner
• DataInputStream etc.

InputStreamReader class:InputStreamReader class can be used to read data from keyboard.It


performs two tasks: 1.connects to input stream of keyboard
2.converts the byte-oriented stream into character-oriented stream
BufferedReader class:BufferedReader class can be used to read data line by line by readLine()
method.
In below example, we are connecting the BufferedReader stream with the InputStreamReader
stream for reading the line by line data from the keyboard.

import java.io.*;
class IODemo
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}

Output:
Enter your name Abc
Welcome Abc

3
3
Example2:In this example, we are reading and printing the data until the user prints stop.

import java.io.*;
class IODemo2
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(name.equals("stop"))
{
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}

3
4
Output:Enter data:
Amit data is:
Amit

Enter data: 10
data is: 10
Enter data:
stop data is:
stop

Reading the data from console(keyboard) using Scanner


class Scanner Class:

The Scanner class breaks the input into tokens using a delimiter which is whitespace
bydefault. It provides many methods to read and parse various primitive values.

3
4
Commonly used methods of Scanner class
Method Description
public String next() returns the next token from the scanner
public String nextLine() moves the scanner position to the next line and returns the value as
a string.
public byte nextByte() scans the next token as a byte.
public short nextShort() scans the next token as a short value.
public int nextInt() scans the next token as an int value
public long nextLong() scans the next token as a long value.
public float nextFloat() scans the next token as a float value.
public double nextDouble() scans the next token as a double value

Example of the Scanner class which reads the int, string and double value as an input:

import java.util.Scanner;
class ScannerTest
{
public static void main(String args[])
{

Scanner sc=new Scanner(System.in);


System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);

}
}

3
5
Output:Enter your rollno
111

Enter your
name Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000

2.3.5 File class

The java.io package include a File class for creating files and directories.

The File class contain several methods for supporting the various operations such as

• Creating a file
• Opening a file
• Closing a file
• Deleting a file
• Getting name of the file
• Renaming a file
• Getting the size of the file
• Checking the existence of a file
• Checking whether the file is writable.
• Checking whether the file is

readable Sntax for creating an object


File fileobject=new File(“file name”);
to File class Example:

File infile=new File(“demo.txt”);


3
6
2.3.6 Reading and Writing files

• To perform read or write operation the file must be opened first.This is done by creating a file stream
and then linking it to the filename
• A file stream can be defined using the classes of Reader/InputStream for reading data and
Writer/OutputStream for writing data.

• The constructor of Stream classes may be used to assign the desired filenames to the file stream
objects.

Commonly Stream class used for Reading and Writing files:

Source Characters Bytes


/Destination Read Write Read Write
File FileReader FileWriter FileInputStream FileOutputStream

Reading/Writing Characters:

• The subclasses of Reader and Writer implements streams that handle characters.
• The two subclasses used are

➢ FileReader-for reading characters


➢ FileWriter –for writing characters

3
7
Example to copy contents of file where file name are passed through command prompt (“input.txt” into file

“output.txt”)

//copying characters from one file into


another import java.io.*;
class CopyCharacters
{
public static void main(String args[])
{
//Declare and create input and output
file File inFile=new File(arsg[0]);
File outFile=new File(args[1]);
FileReader ins=null;//creates file stream
ins FileWriter outs=null;//creates file
stream outs try
{
ins=new FileReader(inFile); //opens inFile
outs=new FileWriter(outFile);//opens outFile
//read and write till the
end int ch;
while((ch=ins.read())!=
-1)
{
outs.write(ch);
}
}
catch(IOException e)
{
System.out.println(e
); System.exit(-1);
}
finall
y
{ try
{

ins.close();
outs.close();
}
catch(IOException e)
{
}

}
}
}
C:\>Javac CopyCharacters.java

C:\>java CopyCharacters input.txt output.txt

Reading/Writing Bytes

• The subclasses of Reader and Writer implements streams that handle bytes.
• The two subclasses used are

➢ FileInputStream r-for reading bytes


➢ FileOutputStream r –for writing bytes
➢ Example to copy contents of file “in.txt” into file “out.txt”

//copying Bytes from one file into


another import java.io.*;

class CopyBytes

public static void main(String args[])

//Declare and create input and output


file File inFile=new File("in.txt");

File outFile=new File("out.txt");


FileInputStream ins=null;//creates file
stream ins

FileOutputStream outs=null;//creates file stream outsbyte


byteRead byte byteRead;

try

ins=new FileInputStream (inFile); //opens inFile


outs=new FileOutputStream (outFile);//opens
outFile

//read and write bytes till the


end do 3
9
{

byteRead=(byte)ins.read();

outs.write(byteRead);

}while(byteRead!=-1);

catch(IOException e)

System.out.println(e);

finally

3
9
try
{

ins.close();

outs.close();

catch(IOException e)

{
System.out.println(e);

}
}

4
0
2.3.7 Random Access Files
• RandamAccessFile class supported by java.io package allows us to create files that can be used
for reading and writing data with randam access.
• This class implements DataInput,and DataOutput and Closeable Interfaces
• It supports positioning request that means we can position the file pointer with in the file.
• It has two constructors

RandamAccessFile(File fileObj,String access)throws FileNotFoundException


RandamAccessFile(String filename,String access)throws FileNotFoundException
In both cases,access determines what type of file access is permited.

Access Purpose
r File opened for reading purpose
rw File opened for read-write purpose
rws File opened for read-write purpose and every change to ythe file’s data or ymetadata will be
immediately written to physical device
rwd File opened for read-write purpose and every change to ythe file’s data will be immediately
written to physical device

The method seek() is used to set the current position of the file pointer

Syntax:

void seek(long newPos)throws IOException

4
0
Here,newPos specifies the new position,in bytes,of the file pointer from the beginning of the file.

//writing and reading with random access


import java.io.*;
class RandomIO
{
public static void main(String args[])
{
RandamAccessFile file=null;
try
{
file=new RandomAccessFile(“rand.dat”, “rw”);
//Writing to the file
file.writeChar(‘x’);
file.writeInt(333);
file.writeDouble(3.1412);
file.seek(0);//go to the beginning
System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());
file.seek(2); //go to the second item
System.out.println(file.readInt());
//go to the end and append false to the file
file.seek(file.length());
file.writeBoolean(false);
file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
catch(IOException e)
{
System.out.println(e);
}

Output:

x
3
3
3
3.1412
333
False

4
1
Explanation of the program

1. .Writes three items of data i.e


x

3
3
3
3.1412
2. Brings the file pointer to the beginning
3. Reads and display all the 3
iteam i.e x
333
3.1412
4. Takes the pointer to the second item and then reads and displays the second
item i.e 333
5. Places thepointer at the end and then adds a Boolean item to the file
6. Finally,takes pointer to the fourth item and display it.
7. At the end,closes the file

2.3.8 Console Class

• Console class is used to read from and write to the console.


• It implements the Flushable interface
• Console supplies no constructor ,a console object is obtained by calling
System.console() Syntax:
public static Console console ( )

If the console is available,its reference is returned other wise null is

returned. Below table gives the methods provided by Console class

4
2
Me Description
tho
d
public String readLine() used to read a single line of text from the console
public String readLine(String fmt,Object... args) it provides a formatted prompt then reads the
single line of text from the console.
public char[] readPassword() used to read password that is not being displayed on
the console.
public char[] readPassword(String fmt,Object... it provides a formatted prompt then reads the
args)
password that is not being displayed on the console.

void flush() Causes buffered output to be written physically to


the console
Console printf(String fmtString,Object …args) Writes args to the console using the format
specified by fmtstring
Reader reader() Returns a reference to Reader connected to the
console
PrintWriter writer() Returns a reference to the Writer connected to the
console

4
2
Example on Reading Console Input And Writing Console Output

import java.io.*;
class ConsoleDemo
{
public static void main(String args[])
{
String str;
Console con;
con=System.Console();
if (con==null)
return;
str=con.readLine(“Enter a string:”);
con.printf(“Here is ur string: %s”,str);
}
}

Output:

Enter a string: Have a nice day

Here is ur string: Have a nice day

4
3
Unit_ II previously asked 2 and 3 marks
Questions
1. List the byte stream classes[3 M]
2. Explain about implicit and explicit import statement[3]
3. How to create and access a package? [3]
4. Write about the random access file operations[3]
5. What is a package? How to define it and access it? [3]
6. Differentiate class, abstract class and interface. [2]
7. How to create and use a package in Java program? [3]
8. Define a Package? What is its use in java? Explain. [2]
9. List out the benefits of Stream oriented I/O. [3]
10. How to define a package in Java? [2]
11. Contrast between abstract class and interface. [3]
12. What are the methods available in the character streams? [2]
13. What is the significance of the CLASSPATH environment variable in
creating/using a package?[3]
14. What is Console class? What is its use in java? [2]

5
5
Unit –II previous asked Essay Questions

1. How to define a package? How to access, import a package? Explain with examples[ 5 marks]
2. Explain the various access specifiers are used in java.[5 m]
3. Write a program to implement the operations of random access file [5 m]
4. Explain the file management using File class.[5m]
5. What is a java package?What is CLASSPATH? Explain how to create and access a java package
with an example. .[5m]
6. Create an interface with at least one method and implement that interface by within a method
which returns a reference to your interface.[5m]
7. Write a program to compute an average of the values in a file.[5m]
8. Explain multilevel inheritance with the help of abstract class in your program. .[5m]
9. Can inheritance be applied between interfaces? Justify your answer. .[5m]
10. Differentiate between interface and abstract class. .[5m]
11. Write a program to copy the contents of file1 to file 2. Read the names of files as command line
arguments.[5m]
12. What support is provided by File class for file management? Illustrate with suitable scenarios. .[5m]
13. What is an interface? What are the similarities between interfaces and classes? .[5m]
14. How can you extend one interface by the other interface? Discuss. .[5m]
15. Discuss about CLASSPATH environment variables. [5m]
16. Discuss the different levels of access protection available in Java. [5m]
17. What is type wrapper? What is the role of auto boxing? [5m]
18. Explain the process of defining and creating a package with suitable examples. [5m]
19. Give an example where interface can be used to support multiple inheritance. [5m]
20. Describe the process of importing and accessing a package with suitable examples.[5m]
21. How to design and implement an interface in Java? Give an example[5m]
22. Give an example where interface can be used to support multiple inheritance. [5m]
23. What are the methods available in the Character Streams? Discuss. [5m]
24. Distinguish between Byte Stream Classes and Character Stream Classes. [5m]
25. What is the accessibility of a public method or field inside a nonpublic class or interface?
Explain. [5m]

56

You might also like