0% found this document useful (0 votes)
3 views47 pages

Unit IV - Notes

The document provides an overview of inheritance, packages, and interfaces in Java. It explains key concepts such as inheritance, member access, method overriding, dynamic method dispatch, abstract classes, and interfaces, along with examples and syntax. Additionally, it discusses the use of the 'final' keyword to prevent modifications, method overriding, and inheritance.
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)
3 views47 pages

Unit IV - Notes

The document provides an overview of inheritance, packages, and interfaces in Java. It explains key concepts such as inheritance, member access, method overriding, dynamic method dispatch, abstract classes, and interfaces, along with examples and syntax. Additionally, it discusses the use of the 'final' keyword to prevent modifications, method overriding, and inheritance.
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/ 47

Unit I V Inheritance, Packages and Interfaces

Inheritance:
• Inheritance can be defined as the process where one class acquires the properties of
another class

• The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
• Inheritance represents the IS-A relationship, also known as parent-child relationship.
• Advantages of inheritance:
• Code reusability
• Used in method overriding (so runtime polymorphism can be achieved).
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class.
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()
{
1
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

System.out.println("i+j+k: " + (i+j+k));


}
}
class SimpleInheritance
{
public static void main(String args [])
{
B subOb = new B();

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


subOb.i = 7;
subOb.j = 8;
subOb.k = 9;

System.out.println("Contents of subOb: ");


subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}

Member Access and Inheritance


Although a subclass includes all of the members of its super class, it cannot access those
members of the super class that have been declared as private. For example, consider the
following simple class hierarchy:

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

class A
{
int i; // public by default
private int j; //Private to A
2
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

void setij(int x, int y)


{
i = x;
j = y;
}
}
class B extends A
{
int total;
void sum()
{
total = i + j; //A's j is not accessible here
}
}
class SimpleInheritance2
{
public static void main(String args[])
{
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}

A super class variable can reference a subclass object:


A reference variable of a super class can be assigned a reference to any subclass derived
from that super class.
Ex:
class A
{
void callMe()
{
System.out.print("Hello");
}
}
3
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

class B extends A
{
void callMe()
{
System.out.print("Hi ");
}
}
class Reference
{
public static void main(String args[])
{
A ref;
B b = new B();
ref = b;
ref.callMe();
}
}

Output: Hi

Using super
Whenever the derived class inherits the base class features, there is a possibility that
base class features are similar to derived class features and JVM gets an ambiguity. To
overcome this, super is used to refer super class properties.
The super keyword in java is a reference variable that is used to refer parent class. The
keyword “super” came into the picture with the concept of Inheritance. It is majorly used in the
following contexts:

– super is used to refer immediate parent class instance variable.


super.parent_instance_variable_name;
– super is used to invoke immediate parent class method
super.parent_class_method_name();
– super is used to invoke immediate parent class constructor.
super(arglist); // parameterized constructor
super(); //default

4
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

Usage 1. - Using super to refer super class property


class Vehicle
{
int speed=50;
}
class Bike extends Vehicle
{
int speed=100;
void display()
{
System.out.println("Vehicle Speed:"+super.speed);//will print speed of vehicle
System.out.println("Bike Speed:"+speed);//will print speed of bike
}
}
class SuperVarible
{
public static void main(String args[])
{
Bike b=new Bike();
b.display();
}
}

Output:

Usage 2. - super is used to invoke immediate parent class method

class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}

class Faculty extends Student


{
5
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

void message()
{
System.out.println("Good Morning Students");
}
void display()
{
message();//will invoke or call current class message() method
super.message();//will invoke or call parent class message() method
}
}
class SuperClassMethod
{
public static void main(String args[])
{
Faculty f=new Faculty();
f.display();
}
}

Output:

Usage 3. - super is used to invoke immediate parent class constructor


class Vehicle
{
Vehicle( )
{
System.out.println("Vehicle is created");
}
}

class Bike extends Vehicle


{
Bike()
{
super( );//will invoke parent class constructor
System.out.println("Bike is created");
}

}
class SuperClassConst
{
6
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

public static void main(String args[])


{
Bike b=new Bike();
}
}

Output:

Calling Constructors:

Constructors are called in order of derivation, from super class to sub class. Further,
since super( ) must be the first statement executed in a subclass’ constructor, this order is the
same whether or not super( ) is used. If super( ) is not used, then the default constructor of
each super class will be executed. The following program illustrates when constructors are
executed:
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A
{
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingConstructor
{
public static void main(String args[])
{
7
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

C c = new C();
}
}

Output:

Method Overriding:

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.
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);
8
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

k = c;
}
// display k – this overrides show() in A
void show()
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

Output:

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.
Example: //A Superclass Variable Can Reference to a Subclass Object
class A
{
void callMe()
{
System.out.println("Inside A");
}
}
class B extends A
{
void callMe()
{
System.out.println("Inside B");
}
}

class C extends B
{
9
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

void callMe()
{
System.out.println("Inside C");
}
}
class DynamicMethodDispatch
{
public static void main(String args[])
{
A a=new A();
B b = new B();
C c = new C();
A ref;
ref = a;
ref.callMe();

ref = b;
ref.callMe();

ref=c;
ref.callMe();
}
}

Output:

Applying Method Overriding:

import java.util.*;

class Student
{
int n;
String name;
void read()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no and Name");
n=s.nextInt();
name=s.nextLine();

}
10
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

void show()
{
System.out.println("No:"+n);
System.out.println("Name:"+name);
}
}
class ITStudent extends Student
{
void read()
{
super.read();
}
void show()
{
super.show();
}
}
class CSEStudent extends Student
{
void read()
{
super.read();
}
void show()
{
super.show();
}

}
class ECEStudent extends Student
{
void read()
{
super.read();
}
void show()
{
super.show();
}
}
class MainMethod
{
public static void main(String ar[])
{
ITStudent it=new ITStudent();
CSEStudent cse=new CSEStudent();
11
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

ECEStudent ece=new ECEStudent();

Student sref;

sref=it;
sref.read();
sref.show();

sref=cse;
sref.read();
sref.show();

sref=ece;
sref.read();
sref.show();
}
}

Abstract Class

• An abstract class is a class that contains one or more abstract methods.


• An abstract method is a method without method body.
Syntax:
abstract return_type method_name(parameter_list);
• An abstract class can contain instance variables, constructors, concrete methods in
addition to abstract methods.
• All the abstract methods of abstract class should be implemented in its sub classes.
• If any abstract method is not implemented in its subclasses, then that sub class must be
declared as abstract.
• We cannot create an object to abstract class, but we can create reference of abstract
class.
• Also, you cannot declare abstract constructors or abstract static methods.
Example 1: Java program to illustrate abstract class.
abstract class MyClass
{
abstract void calculate(double x);
}
class Sub1 extends MyClass
{
void calculate(double x)
12
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

{
System.out.println("Square :"+(x*x));
}
}
class Sub2 extends MyClass
{
void calculate(double x)
{
System.out.println("Square Root :"+Math.sqrt(x));
}
}
class Sub3 extends MyClass
{
void calculate(double x)
{
System.out.println("Cube :"+(x*x*x));
}
}
class AC
{
public static void main(String arg[])
{
Sub1 obj1=new Sub1();
Sub2 obj2=new Sub2();
Sub3 obj3=new Sub3();

obj1.calculate(20);
obj2.calculate(20);
obj3.calculate(20);
}
}

Example 2: Java program to illustrate abstract class.

// 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()
13
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

{
System.out.println("B's implementation of callme.");
}
}

class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}

Uses of Final:

Final can be used in three ways:


• To prevent modifications to the instance variable
• To Prevent method overriding
• To prevent inheritance
Use 2: To prevent method overriding
class Vehicle
{
final void run()
{
System.out.println("running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("running safely with 100kmph");
}
}

class FinalMethod
{
public static void main(String args[])
{
Bike b= new Bike();
b.run();
14
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

}
}
Error Information:

Use 3: To prevent inheritance


final class Vehicle
{
void run()
{
System.out.println("running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("running safely with 100kmph");
}
}

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

15
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

Interfaces:
 A named collection of method declarations.
 A Java interface is a collection of constants and abstract methods
 Since all methods in an interface are abstract, the abstract modifier is usually left off
 Using interface, you can specify what a class must do, but not how it does.
 Interface fields are public, static and final by default, and methods are public and abstract.

Advantages of interfaces:
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritances.

Syntax:
access_specifier interface interfae_name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

16
PGMCOE,Wagholi.
Unit I V Inheritance, Packages and Interfaces

Implementing Interfaces:
• Once an interface has been defined, one or more classes can implement that interface.
• To implement an interface, include the implements clause in a class definition, and then
create the methods defined by the interface.
• The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface1 [,interface2...]] {
// class-body
}
• If a class implements more than one interface, the interfaces are separated with a
comma.
• The methods that implement an interface must be public. Also, the type signature of
implementing method must match exactly the type signature specified in interface
definition.
Example 1: Write a java program to implement interface.
interface Moveable
{
int AVG_SPEED=30;
void Move();
}
class Move implements Moveable
{
void Move(){
System .out. println ("Average speed is: "+AVG_SPEED );
}
}
class Vehicle
{
public static void main (String[] arg)
{
Move m = new Move();
m.Move();
}
}

17
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

Example 2: Write a java program to implement interface.


interface Teacher
{
void display1();
}
interface Student
{
void display2();
}
class College implements Teacher, Student
{
public void display1()
{
System.out.println("Hi I am Teacher");
}
public void display2()
{
System.out.println("Hi I am Student");
}
}
class CollegeData
{
public static void main(String arh[])
{
College c=new College();
c.display1();
c.display2();
}
}

Accessing implementations through interface references:


We can declare variables as object references that use an interface rather than a class
type. Any instance of any class that implements the declared interface can be referred to by such
a variable. When you call a method through one of these references, the correct version will be
called based on the actual instance of the interface being referred to. This is one of the key
features of interfaces. The method to be executed is looked up dynamically at run time,
allowing classes to be created later than the code which calls methods on them.

18
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

Ex:
interface Test {

void call();
}

class InterfaceTest implements Test {

public void call()


{
System.out.println("call method called");
}
}

public class IntefaceReferences {

public static void main(String[] args)


{
Test f ;
InterfaceTest it= new InterfaceTest();
f=it;
f.call();
}
}

Variables in Interfaces:

We can use interfaces to import shared constants into multiple classes by simply
declaring an interface that contains variables that are initialized to the desired values. When we
include that interface in a class (that is, when you “implement” the interface), all of those
variable names will be in scope as constants. (This is similar to using a header file in C/C++ to
create a large number of #defined constants or const declarations). If an interface contains no
methods, then any class that includes such an interface doesn’t actually implement anything. It
is as if that class were importing the constant fields into the class name space as final variables.

Example: Java program to demonstrate variables in interface.


interface left
{
int i=10;
}
interface right
19
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

{
int i=100;
}
class Test implements left,right
{
public static void main(String args[])
{
System.out.println(left.i);//10 will be printed
System.out.println(right.i);//100 will be printed*/
}
}

Interfaces can be extended:


One interface can inherit another by use of the keyword extends. The syntax is the same
as for inheriting classes. When a class implements an interface that inherits another interface,
it must provide implementations for all methods defined within the interface inheritance chain.

Example: Java program to demonstrate interfaces can be extended with extend keyword.
interface Teacher
{
void display1();
}
interface Student
{
void display2();
}
interface T_S extends Teacher, Student
{
void display3();
}
class College implements T_S
{
public void display1()
{
System.out.println("Hi I am Teacher");
}
public void display2()
{
System.out.println("Hi I am Student");
}
public void display3()
{
System.out.println("Hi I am Teacher_Student");

20
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

}
}
class Class_Interface
{
public static void main(String arh[])
{
College c=new College();
c.display1();
c.display2();
c.display3();
}

Example 2: Java program to implement interface and inheriting the properties from a class.
interface Teacher
{
void display1();
}
class Student
{
void display2()
{
System.out.println("Hi I am Student");
}
}
class College extends Student implements Teacher
{
public void display1()
{
System.out.println("Hi I am Teacher");
}
}
class Interface_Class
{
public static void main(String arh[])
{
College c=new College();
c.display1();
c.display2();
}
}

21
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

Difference between Interface and Abstract class:

Abstract Class Interface

Contains some abstract methods and some


Only abstract methods
concrete methods

Contains instance variables Only static and final variables

Doesn’t support multiple inheritance Supports

public class Person implements


public class Apple extends Food { … }
Student,Athlete,Chef { … }

Packages:

• A Package can be defined as a grouping of related types(classes, interfaces)


• A package represents a directory that contains related group of classes and interfaces.
• Packages are used in Java in order to prevent naming conflicts.
• There are two types of packages in Java.
1. Pre-defined Packages(built-in)
2. User defined packages
Pre-defined Packages:
Package
Description
Name
Contains language support classes (for e.g classes which defines
java.lang primitive data types, math operations, etc.). This package is
automatically imported.
java.io Contains classes for supporting input / output operations.
Contains utility classes which implement data structures like Linked
java.util List, Hash Table, Dictionary, etc and support for Date / Time operations.
This package is also called as Collections.

java.applet Contains classes for creating Applets.

Contains classes for implementing the components of graphical user


java.awt
interface ( like buttons, menus, etc. ).

22
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

java.net Contains classes for supporting networking operations.


This package helps to develop GUI like java.awt. The ‘x’ in javax
represents that it is an extended package which means it is a package
javax.swing
developed from another package by adding new features to it. In fact,
javax.swing is an extended package of java.awt.
This package helps to connect to databases like Oracle/Sybase/Microsoft
java.sql
Access to perform different operations.

Defining a Package(User defined):


To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the specified
package. The package statement defines a name space in which classes are stored. If you omit
the package statement, the class names are put into the default package, which has no name.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package.
For example, the following statement creates a package called MyPackage:
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called MyPackage.
Remember that case is significant, and the directory name must match the package name
exactly. More than one file can include the same package statement.
The package statement simply specifies to which package the classes defined in a file
belong. It does not exclude other classes in other files from being part of that same package.
Most real-world packages are spread across many files. You can create a hierarchy of packages.
To do so, simply separate each package name from the one above it by use of a period. The
general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system. For
example, a package declared as
package java.awt.image;

23
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

Example: Package demonstration


package pack;
public class Addition
{
int x,y;
public Addition(int a, int b)
{
x=a;
y=b;
}
public void sum()
{
System.out.println("Sum :"+(x+y));
}
}
Step 1: Save the above file with Addition.java

package pack;
public class Subtraction
{
int x,y;
public Subtraction(int a, int b)
{
x=a;
y=b;
}
public void diff()
{
System.out.println("Difference :"+(x-y));
}
}

Step 2: Save the above file with Subtraction.java


Step 3: Compilation
To compile the java files use the following commands
javac -d directory_path name_of_the_java file
Javac –d . name_of_the_java file
Note: -d is a switching options creates a new directory with package name. Directory
path represents in which location you want to create package and . (dot) represents
current working directory.
24
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

Step 4: Access package from another package


There are three ways to use package in another package:
1. With fully qualified name.
class UseofPack
{
public static void main(String arg[])
{
pack.Addition a=new pack.Addition(10,15);
a.sum();
pack.Subtraction s=new pack.Subtraction(20,15);
s.difference();
}
}
2. import package.classname;

import pack.Addition;
import pack.Subtraction;
class UseofPack
{
public static void main(String arg[])
{
Addition a=new Addition(10,15);
a.sum();
Subtraction s=new Subtraction(20,15);
s.difference();
}
}
3. import package.*;
import pack.*;
class UseofPack
{
public static void main(String arg[])
{
Addition a=new Addition(10,15);
a.sum();
Subtraction s=new Subtraction(20,15);
s.difference();
}
}
25
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

Note: Don’t place Addition.java, Subtraction.java files parallel to the pack directory. If
you place JVM searches for the class files in the current working directory not in the
pack directory.

Access Protection
• Access protection defines actually how much an element (class, method, variable) is
exposed to other classes and packages.
• There are four types of access specifiers available in java:
1. Visible to the class only (private).
2. Visible to the package (default). No modifiers are needed.
3. Visible to the package and all subclasses (protected)
4. Visible to the world (public)

Example:
The following example shows all combinations of the access control modifiers. This
example has two packages and five classes. The source for the first package defines three
classes: Protection, Derived, and SamePackage.
Name of the package: pkg1
This file is Protection.java
package pkg1;

public class Protection


{
int n = 1;
private int n_priv = 2;
protected int n_prot = 3;
public int n_publ = 4;

26
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces

public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_priv = " + n_priv);
System.out.println("n_prot = " + n_prot);
System.out.println("n_publ = " + n_publ);
}
}

This is file Derived.java:


package pkg1;

class Derived extends Protection


{
Derived()
{
System.out.println("Same package - derived (from base) constructor");
System.out.println("n = " + n);

/* class only
* System.out.println("n_priv = "4 + n_priv); */

System.out.println("n_prot = " + n_prot);


System.out.println("n_publ = " +n_publ);
}
}

This is file SamePackage.java

package pkg1;

class SamePackage
{
SamePackage()
{
Protection pro = new Protection();
System.out.println("same package - other constructor");
System.out.println("n = " + pro.n);

/* class only
* System.out.println("n_priv = " + pro.n_priv); */

System.out.println("n_prot = " + pro.n_prot);


27
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

System.out.println("n_publ = " + pro.n_publ);


}
}

Name of the package: pkg2

This is file Protection2.java:

package pkg2;

class Protection2 extends pkg1.Protection


{
Protection2()
{
System.out.println("Other package-Derived (from Package 1-Base)
Constructor");

/* class or package only


* System.out.println("n = " + n); */

/* class only
* System.out.println("n_priv = " + n_priv); */

System.out.println("n_prot = " + n_prot);


System.out.println("n_publ = " + n_publ);
}
}

This is file OtherPackage.java


package pkg2;

class OtherPackage
{
OtherPackage()
{
pkg1.Protection pro = new pkg1.Protection();

System.out.println("other package - Non sub class constructor");

/* class or package only


* System.out.println("n = " + pro.n); */

/* class only
* System.out.println("n_priv = " + pro.n_priv); */

/* class, subclass or package only


28
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

* System.out.println("n_prot = " + pro.n_prot); */

System.out.println("n_publ = " + pro.n_publ);


}
}

If you want to try these t two packages, here are two test files you can use. The one for
package pkg1 is shown here:

/* demo package pkg1 */

package pkg1;

/* instantiate the various classes in pkg1 */


public class Demo
{
public static void main(String args[])
{
Derived obj2 = new Derived();
SamePackage obj3 = new SamePackage();
}
}

The test file for package pkg2 is

package pkg2;

/* instantiate the various classes in pkg2 */


public class Demo2
{
public static void main(String args[])
{
Protection2 obj1 = new Protection2();
OtherPackage obj2 = new OtherPackage();
}
}

29
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

30
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

Java Package

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

Package in java can be categorized in two form, built-in package and user-defined

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

util, sql etc. Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to
package");
}}

31
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

How to compile java package

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

given below: javac -d directory javafilename


How to run java package program

To Compile: javac -d . Simple.java


To Run: java mypack.Simple

Using fully qualified name

Example of package by import fully qualified name


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//saveby B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

32
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.

What is exception

In java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types of
exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions

1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.

2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptionsarenotchecked at compile-timeratherthey arechecked at runtime.

3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionErroretc.

33
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

Hierarchy of Java Exception classes

Checked and UnChecked Exceptions

34
PGMCOE, Wagholi.
Java try block

Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
Unit IV Inheritance, Packages and Interfaces
Java try block must be followed by either catch or finally block.

Syntax of java try-catch

1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block

1. try{
2. //code that may throw exception
3. }finally{}

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block

only. You can use multiple catch block with a single try.

Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.

public class Testtrycatch1{


public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the
code...");
}}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed (in such case, rest of
the code... statement is not printed).

There can be 100 lines of code after exception. So all the code after exception will not be
executed.

Solution by exception handling

Let's see the solution of above problem by java try-catch block.


public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticExceptione){System.out.println(e);
35
PGMCOE, Wagholi.
} System.out.println("rest of the code...");
}}
1. Output:
UnitException
IV in thread main java.lang.ArithmeticException:/ by zero Packages and Interfaces
Inheritance,
rest of the code...

Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.

Java Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.

Let's see a simple example of java multi-catch block.

1. public class TestMultipleCatchBlock{


2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){System.out.println("task1 is completed");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");
9. }
10. catch(Exception e){System.out.println("common task completed");
11. }
12. System.out.println("rest of the code...");
13. } }

Output:task1 completed
rest of the code...

Java nested try example

Let's see a simple example of java nested try block.

class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{

36
PGMCOE, Wagholi.
int a[]=new int[5];
a[5]=4;
Unit IV Inheritance, Packages and Interfaces
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
1. }
Java finally block

Java finally block is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not. Java finally

block follows try or catch block.

Usage of Java finally

Case 1

Let's see the java finally example where exception doesn't occur.

class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...

Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.

37
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

1. throw exception;

Java throw keyword example

In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.

1. public class TestThrow1{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
} }

Output:

Exception in thread main java.lang.ArithmeticException:not valid


Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.

Syntax of java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }
4.

Java throws example

Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
38
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow..."); } }
Output:
exception handled
normal flow...

Java Custom Exception

If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let's see a simple example of java custom exception.

class InvalidAgeException extends Exception{


InvalidAgeException(String s){
super(s);
}}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
39
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

}catch(Exception m){System.out.println("Exception occured: "+m);}

System.out.println("rest of the code...");


}}

Output:Exception occured: InvalidAgeException:not valid rest of the code…

Managing I/O :

The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination.
The stream in the java.io package supports many data such as primitives, object, localized
characters, etc.

Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −

 InPutStream − The InputStream is used to read data from a source.

 OutPutStream − The OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly
used examples one by one −

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used
classes are, FileInputStream and FileOutputStream. Following is an example which
makes use of these two classes to copy an input file into an output file −

Example:

40
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

import java.io.*;

public class CopyFile {

public static void main(String args[]) throws IOException {

FileInputStream in = null;

FileOutputStream out = null;

try {

in = new FileInputStream("input.txt");

out = new FileOutputStream("output.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);

}finally {

if (in != null) {

in.close();

if (out != null) {

out.close();

}} }}

41
PGMCOE, Wagholi.
Now let's have a file input.txt with the following content −

This is test for copy file.


Unit IV Inheritance, Packages and Interfaces
As a next step, compile the above program and execute it, which will result in creating output.txt file with
the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the
following −

$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java
Character streams are used to perform input and output for 16-bit unicode. Though there are many
classes related to character streams but the most frequently used classes are, FileReader and
FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at
a time.

We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode
characters) into an output file −
Example

import java.io.*;

public class CopyFile {

public static void main(String args[]) throws IOException {

42
PGMCOE, Wagholi.
FileReader in = null;
Unit IV Inheritance, Packages and Interfaces
FileWriter out =

null; try {

in = new FileReader("input.txt");

out = new

FileWriter("output.txt"); int c;

while ((c = in.read()) != -1) {

out.write(c);}

}finally {

if (in != null) {

in.close();}

if (out != null) {

out.close();

}} }}

Now let's have a file input.txt with the following content −

This is test for copy file.


As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code in
CopyFile.java file and do the following −

$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program
can take input from a keyboard and then produce an output on the computer screen. Java
provides the following three standard streams −

 Standard Input − This is used to feed the data to user's program and usually a keyboard
is used as standard input stream and represented asSystem.in.

43
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

 Standard Output − This is used to output the data produced by the user's
program and usually a computer screen is used for standard output
stream and represented as System.out.

 Standard Error − This is used to output the error data produced by the
user's program and usually a computer screen is used for standard error
stream and represented as System.err.

Following is a simple program, which creates InputStreamReader to read


standard input stream until the user types a "

44
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

Reading and Writing Files


As described earlier, a stream can be defined as a sequence of data. The
InputStream is used to read data from a source and the OutputStream is used
for writing data to a destination.

Here is a hierarchy of classes to deal with Input and Output streams.

The two important streams are FileInputStream and


FileOutputStream

45
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

FileInputStream
This stream is used for reading data from the files. Objects can be
created using the keyword new and there are several types of
constructors available.

Following constructor takes a file name as a string to create an input stream

InputStream f = new FileInputStream("C:/java/hello");


object to read the file −

Following constructor takes a file object to create an input stream object to read

File f = new File("C:/java/hello");


InputStream f = new
the file. First we create a file object using File() method as follows −
FileInputStream(f);

Once you have InputStream object in hand, then there is a list of helper methods
which can be used to read to stream or to do other operations on the stream.

 ByteArrayInputStream

 DataInputStream

FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream
would create a file, if it doesn't already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream

OutputStream f = new FileOutputStream("C:/java/hello")


object to write the file −

Following constructor takes a file object to create an output stream object to


write the file. First, we create a file object using File() method as follows − 46
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces

File f = new File("C:/java/hello");


OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods,
which can be used to write to stream or to do other operations on the stream.
 ByteArrayOutputStream
 DataOutputStream

47
PGMCOE, Wagholi.

You might also like