Вы находитесь на странице: 1из 35

Module III

Classes, Inheritance, Exceptions, Packages, Interfaces


Classes

Class is a logical abstraction which contains data or variables & functions.


Syntax:
class class_name
{
data_type instance_variable1;
data_type instance_variable2;
....
....
....

in
data_type instance_variablen;
data_type method_name(parameter_list)

.
{
//code
ac
}
tu
}
.v

 A class creates new data type.


 Variables declared inside class are called as instance variables.
w

 Functions are also called as methods.


 Variables and methods declared inside a class are called as members of a class.
w

 When multiple objects are created, each object has its own copy of members i.e. data of one
object is different from data of other objects.
w

 Class declaration creates a template, but not an actual object.


How to create an object?
<Class_Name> <Object_Name> = new <Class_Name>();
Once object is created, that object is linked with members of a class. Later use dot operator to
access members of the class.
Example:
class Box
{
double width;
double height;
double depth;
}
Box mybox = new Box( );
Also, object can be created in two steps.
1. Declare Object [ Box mybox; ]
2. Allocate Memory [ mybox = new Box( ); ]
Constructors
• Constructors are member functions of a class.
• Constructors are called at the time of object creation.
• Constructors are required to initialize the data members for objects created to a
class.
• Constructors do not return any value, even void.
• Constructors have same name as that of class.
• Constructors are non-static members of a class.

in
• Different types of constructors are
• Zero parameterized constructors

.


Parameterized constructors
Copy Constructors
ac
Zero parameterized constructors
tu
 It does not receive any arguments at the time of calling constructor.
Example
.v

public class zeroConstructor {


int a;
w

zeroConstructor()
{
System.out.println("Zero Parameter Constructuor Called");
w

a = 10;
System.out.println("Data member a is initialized to " +a);
w

}
public static void main(String[] args) {
zeroConstructor z = new zeroConstructor();
}
}
Output:

Parameterized constructors
 In these method constructors receives one or more parameters.
public class parameterConstructor {
int a;
parameterConstructor(int x)
{
System.out.println("Parameterized Constructuor Called");
a = x;
System.out.println("Data member a is initialized to " +a);
}
public static void main(String[] args) {
parameterConstructor z = new parameterConstructor(20);
}
}
Output:

this pointer

in
 this is a reference to object of the class.
 this can be used to refer current class instance variable.

.

ac
this can be used to invoke current class method .
public class parameterConstructor {
int a, b;
tu
parameterConstructor(int a, int b)
{
System.out.println("Parameterized Constructor Called");
.v

this.a = a;
this.b = b;
w

System.out.println("Data member a is initialized to " +a);


System.out.println("Data member a is initialized to " +b);
w

}
public static void main(String[] args) {
parameterConstructor z = new parameterConstructor(30, 40);
w

}
}
Output:
Parameterized Constructor Called
Data member a is initialized to 30
Data member a is initialized to 40
Instance Variable Hiding
 If there is a local variable in method with same name as instance variable, then
the local variable hides the instance variable.
public class instanceVariable {
int a = 10;
void display()
{
int a = 20;
System.out.println("Value of Instance Variable is "
+this.a);
System.out.println("Value of Local Variable is " +a);
}
public static void main(String[] args) {
instanceVariable i = new instanceVariable();
i.display();
}
}
Output:
Value of Instance Variable is 10
Value of Local Variable is 20
Garbage Collection

in
 When an object is dereferenced, the memory allocated to the object will be
reclaimed automatically. This mechanism is called garbage collection.

.

ac
Garbage collector removes the unreferenced objects automatically from the heap
memory.
 Garbage collector is a part of JVM.
tu
How Garbage collector works
1. STUDENT s = new STUDENT( );  Memory allocated to object s.
.v

s = null;  Object is dereferenced, Now garbage collector frees the memory allocated
to members of object automatically.
w

2. STUDENT s1 = new STUDENT( );  Memory allocated to s1


w

STUDENT s2 = new STUDENT( );  Memory allocated to s2


s1 = s2;  Assigned s2 as reference to s1. Hence, s1 and s2 pointing to same data
w

members. Here, Garbage collector frees memory allocated to members of s1.

Finalize Method
 If an object is required to perform some task before it is deleted, the task should
be written in final method.
 The final method is executed just before collecting the garbage.
 Specify the actions to be performed by object before destroying in final method.
 The general form of final method is
protected void finalize( )
{
//Actions to be performed
}
Example:
public class finalGarbage {
int a = 10;
protected void finalize()
{
System.out.println("From Final Method");
}
public static void main(String[] args) {
finalGarbage fG = new finalGarbage();
finalGarbage fG1 = new finalGarbage();
fG = fG1;
System.out.println("Program Terminated");
System.gc();
}

in
}
Output:

.
Program Terminated
From Final Method
ac
Inheritance
tu
 It is a mechanism that allows one class to inherit property of another class.
 The class that is inherited is called super class (Parent class).
.v

 The class that inherits the properties of other class is called sub class (Child class).
 The keyword “extends” is used to inherit the properties.
w

 Inheritance represents the IS-A relationship, also known as parent-child relationship.


 Now, Inheritance is a mechanism in which child object inherits the properties and behaviors
w

of parent class.
 The access specifiers determine whether a field or method in a class, can be used or invoked
w

by another method in another class or sub-class.


 Inheritance is used to create new classes based on existing classes.
 Using inheritance, fields and methods of parent class can be used in child class.
 Syntax
class Sub_Class_Name extends Super_Class_Name
{
//Data Members and Methods
}
 In below example, class BIKE is inherited by VEHICLE
Example:
class VEHICLE
{
double mileage;
double price;
VEHICLE()
{
mileage = 20.5;
price = 20500;
}
}
class CAR extends VEHICLE
{
String name = "Swift";
void display()
{
System.out.println("Car Details");

in
System.out.println("Name:" +name);
System.out.println("Mileage:" +mileage);

.
System.out.println("Price:" + price);

}
}
ac
public class singleInheritance {
public static void main(String[] args) {
tu
CAR c1 = new CAR();
c1.display();
.v

}
}
Output:
w

Car Details
Name: Swift
w

Mileage: 20.5
Price: 805000.0
w

The different types of inheritance are as follows


1. Single Inheritance
2. Multilevel Inheritance
VEHICLE
3. Hierarchical Inheritance
float mileage
4. Multiple Inheritance (Not Supported in Java)
float price
5. Hybrid Inheritance.
void read( )
Single Inheritance
 Here the super class is inherited by only one sub class.
 Example,

BIKE
String Make
String Make
void display( )
Example:
class Vehicle
{
int vehicle_speed = 100;
}
public class Bike extends Vehicle {
int bike_speed = 200;
public static void main(String[] args)
{
Bike b = new Bike();
System.out.println("Speed of a vehicle is " + b.vehicle_speed);
System.out.println("Speed of a vehicle is " + b.bike_speed);

in
}
}

.
Output: Speed of a vehicle is 100
Speed of a vehicle is 200
ac
In the above example, Bike object can access the field of own class as well as of Vehicle class i.e.
code re usability.
tu
Multi-Level Inheritance
 Here, sub class created by inheriting super class and new class is created by
inheriting sub class.
.v

A
w
w

B
w

Example 1:
class A
{
A()
{
System.out.println("Class A constructor");
}
}

class B extends A
{
B()
{
System.out.println("Class B constructor");
}
}

public class C extends B {


C()
{
System.out.println("Class C constructor");
}
public static void main(String[] args) {
C Obj = new C();
}

}
Output:
Class A constructor
Class B constructor
Class C constructor

in
 In the above example,
◦ First class A's constructors are called

.
◦ Secondly class B's constructors are called
ac
◦ Lastly class C's constructors are called

Example 2:
class Animal{
tu
void eat()
{
.v

System.out.println("eating...");
}
}
w

class Dog extends Animal{


void bark()
w

{
System.out.println("barking...");
w

}
}
class BabyDog extends Dog{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d = new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:

Hybrid Inheritance
 Here two or more sub classes are inherited from one super class.
class Animal{
void eat()
{
System.out.println("eating...");
}

in
}
class Dog extends Animal{
void bark()

.
{ ac
System.out.println("barking...");
}
}
tu
class Cat extends Animal{
void meow()
.v

{
System.out.println("meowing...");
}
w

}
class TestInheritance3{
w

public static void main(String args[]){


Cat c = new Cat();
w

c.meow();
c.eat();
}
}
Output:
Interface
An interface in java is a blueprint of a class. It has static constants and abstract methods only. The
interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve fully abstraction and multiple
inheritances in Java.
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the
class.
interface printable
{
void print();
}
class Example_Interface implements printable
{
public void print()

in
{
System.out.println("Hello");

.
}
public static void main(String args[])
{
ac
Example_Interface obj = new Example_Interface();
tu
obj.print();
}
}
.v

Multiple Inheritance
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
w

multiple inheritance.
Example of simple interface
w

interface Printable
{
w

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

public static void main(String args[])


{
Multiple_Inheritance obj = new Multiple_Inheritance();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
Method Overriding

in
 Method in super class and sub class has same name and parameters.
 The implementation details of method in sub class are different from its parent

.
class. ac
 When method is called from sub class object, then sub class method is executed.
Example
tu
class VEHICLE1
{
double mileage;
.v

double price;
VEHICLE1()
w

{
mileage = 20.5;
w

price = 20500;
}
void display()
w

{
System.out.println("Name:" +price);
System.out.println("Mileage:" +mileage);
}
}
class CAR1 extends VEHICLE1
{
String name = "Swift";
void display()
{
System.out.println("Car Details");
System.out.println("Price:" + name);
}
}
public class singleInheritance {
public static void main(String[] args) {
CAR1 c1 = new CAR1();
c1.display();
}
}
Output:
Car Details
Price: Swift

Super Class
 A super class is a class that has been extended by another class. It allows the extending class

in
to inherit its state and behaviors.
 It is also called as base class or parent class.

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

 Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
tu
Usage of java super Keyword
.v

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


2. super( ) is used to invoke immediate parent class constructor.
w

3. super is used to invoke immediate parent class method.


w

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

class Vehicle
w

{
int speed = 100;
}
public class Bike extends Vehicle {
int speed = 200;
void display()
{
System.out.println("Speed of a vehicle is " +speed);
//refers to local variable
System.out.println("Speed of a vehicle is "
+super.speed); // refers to super class variable
}
public static void main(String[] args) {
Bike b = new Bike();
b.display();
}
}
Output:
Speed of a vehicle is 200
Speed of a vehicle is 100

2) super is used to invoke parent class constructor

class College{
College()
{
System.out.println("Presently I Am in Parent Class
Constructor");
}

in
}
public class SuperParentConstructor extends College{

.
SuperParentConstructor()
{
super();
ac
System.out.println("Presently I Am in Extended Class
Constructor");
tu
}
public static void main(String[] args) {
.v

SuperParentConstructor spc = new SuperParentConstructor();

}
w

}
Output:
w
w

Abstract Classes and Methods


 It is a process of hiding the implementation details and showing only functionality to the
user.
 The abstract class contains method declarations that are common to sub classes.
 The abstract class may or may not contain function definition.
 The abstract class may or may not contain abstract methods.
 abstract keyword is used to create abstract class or method.
 Objects cannot be created for abstract class.
 Methods declared as abstract do not have their definition in abstract class.
Syntax of abstract class Syntax of abstract method
abstract class <class_name> abstract class <class_name>
{ {
members; abstract void read( );
} }

Example 1:
abstract class Bank
{
abstract void ROI();
void Info()
{
System.out.println("All Banks Must Adhere to the Rules and
Regulations of RBI");
}

in
}
class SBI extends Bank
{

.
void ROI( ) ac
{
System.out.println("Rate of Interest at SBI is 8.5%");
}
}
tu
class CANARA extends Bank
{
.v

void ROI( )
{
System.out.println("Rate of Interest at SBI is 8.8%");
w

}
}
w

public class abstractExample {


public static void main(String[] args) {
sSBI s = new SBI( );
w

CANARA c = new CANARA( );


s.ROI( );
c.ROI( );
s.Info( );
c.Info( );
}
}
Output:
Rate of Interest at SBI is 8.5%
Rate of Interest at SBI is 8.8%
All Banks Must Adhere to the Rules and Regulations of RBI
All Banks Must Adhere to the Rules and Regulations of RBI
Example 2:
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()

in
{
System.out.println("drawing circle");

.
} ac
}
class Testabstraction1
{
tu
public static void main(String args[])
{
Rectangle s = new Rectangle();
.v

s.draw();
}
w

}
Output: drawing rectangle
w

Final
w

 Final is a keyword that has following functionalities.


o Final can be used to create constant variables.
o Final can be used prevent method overriding.
o Final can be used to prevent Inheritance.

Final can be used to prevent method overriding


 When a method in super class is defined as final, such methods cannot be
defined again in sub class.
 Example
class animal
{
final void display()
{
System.out.println("I am in animal class");
}
}
class cat extends animal
{
void display() //Error, redefining final method is not allowed
{
System.out.println("I am in animal class");
}

}
public class finalExample {
public static void main(String[] args){

in
cat c = new cat();
c.display();

.
}
}
Output:
ac
Error
Final can be used to prevent Inheritance
tu
o The class being inherited can be avoided by using final.
.v

o When a class is defined as final, such classes cannot be inherited by any sub
class.
w

Example:
final class animal
w

{
final void display()
w

{
System.out.println("I am in animal class");
}
}
class cat extends animal
{
void display(){
System.out.println("I am in animal class");
}
}
public class finalExample {
public static void main(String[] args){
cat c = new cat();
c.display();
}
}
Output:
Cannot inherit from final class

Object class
o By default, object class is a top most class of all objects in java.
o The objects of Object class can reference to any objects of sub class.
o The methods of this class are
Method Purpose
Object clone( ) Creates new object that is same as object being cloned
boolean equals(Object obj) Determines whether one object is equal to other

in
void finalize( ) Invoked before garbage collector frees the memory

.
Class getClass( ) Obtains the class of an object at run time
int hashCode( )
ac
Returns the hashcode associated with the invoking object

Classes
tu
 It is also called as nested classes.
 Here, one class is declared inside another class.
.v

 Inner classes are used to logically group classes so that program is easy to read and
maintain.
 Syntax of inner class
w

class Java_Outer_Class
w

{
//code
w

class Java_Inner_Class
{
//Code
}
}
Advantages of inner classes
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.
Access Modifiers
Access Modifiers Default private protected Public

Accessible inside the class Yes Yes Yes Yes

Accessible within the subclass inside the same package Yes No Yes Yes

Accessible outside the package No No No Yes

Accessible within the subclass outside the package No No No Yes

Method Overriding

in
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java.

.
Usage of Java Method Overriding

ac
Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
 Method overriding is used for runtime polymorphism
tu
Rules for Java Method Overriding
1. method must have same name as in the parent class
.v

2. method must have same parameter as in the parent class.


Example
w

class Vehicle
{
w

void run()
{
w

System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("Bike is running");
}
public static void main(String args[])
{
Bike obj = new Bike();
obj.run();
}
}
Output: Bike is running
Overloading

 If a class has multiple methods by same name but different parameters, it is known as
Method Overloading.
 Method overloading increases the readability of the program.

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1. Method Overloading by changing number of arguments

in
In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
Example:

.
class Calculation
{
ac
void sum(int a, int b)
tu
{
System.out.println(a+b);
}
.v

void sum(int a, int b, int c)


w

{
System.out.println(a+b+c);
}
w

public static void main(String args[])


w

{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Output:
2. Method Overloading by changing data type of arguments
In this example, we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two double arguments.
class Calculation
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{

in
Calculation obj=new Calculation();
obj.sum(10,20);

.
obj.sum(5.5, 6.5); ac
}
}
tu
Method Overloading Method Overriding
.v

Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.
w

Method overloading is performed within class. Method overriding occurs in two classes that
w

have IS-A (inheritance) relationship.

In case of method overloading, parameter must In case of method overriding, parameter must be
w

be different. same.

Method overloading is the example of compile Method overriding is the example of run time
time polymorphism. polymorphism.

In java, method overloading can't be performed Return type must be same in method overriding.
by changing return type of the method only.
Return type can be same or different in method
overloading. But you must have to change the
parameter.
Exception Handling
The exception handling in java is one of the powerful mechanisms to handle the runtime errors so
that normal flow of the application can be maintained.
What is exception?
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
What is exception handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
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. Let's take a scenario:

in
statement1;
statement2;

.
statement3;
statement4;
ac
statement5;
tu
statement6; //exception occurs
statement7;
.v

statement8;
statement9;
w

statement10;
Suppose there are 10 statements in a program and there occurs an exception at statement 6, rest of
w

the code will not be executed i.e. statement 7 to 10 will not run. If we perform exception handling,
rest of the code will be executed. That is why we use exception handling in java.
1) Checked Exception (Compile Time Exception)
w

 The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions.
 These exceptions are checked at compile time.
 Example: IOException, SQLException etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception (Run Time Exceptions)
 The classes that extend RuntimeException are known as unchecked exceptions.
 These exceptions are not checked at compile time.
 Example: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
3) Error
 Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
 These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.
Common scenarios where exceptions may occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:
Scenario 1: where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
1. int a=50/0; //ArithmeticException

Scenario 2: where NullPointerException occurs

in
If we have null value in any variable, performing any operation by the variable occur a
NullPointerException.
1. String s=null;

.
ac
2. System.out.println(s.length()); // NullPointerException

Scenario 3: where NumberFormatException occurs


tu
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string
variable that have characters, converting this variable into digit will occur
NumberFormatException.
.v

1. String s="abc";
2. int i=Integer.parseInt(s); //NumberFormatException
w

Scenario 4: where ArrayIndexOutOfBoundsException occurs


w

If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
w

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException
There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
try block
 try block is used to enclose the code that might throw an exception. It must be used within
the method.
 try block must be followed by either catch or finally block.
 Syntax
try{
//code that may throw exception
}catch(Exception_class_Name ref){//Things to do when exception occurs }
Example:
Let us understand the problem if we don't use try-catch block.
public class Testtrycatch1
{
public static void main(String args[])

in
{
int data=50/0; //may throw exception

.
}
ac
System.out.println("After Exception");

}
tu
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, “After Exception” is not executed
.v

Solution by Exception Handling.


public class Testtrycatch2
{
w

public static void main(String args[])


{
w

try
{
w

int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM
provides a default exception handler that performs the following tasks:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods where the exception occurred).
 Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
Multiple catch block
If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch
block.
Example:
public class TestMultipleCatchBlock
{
public static void main(String args[])
{
try
{

in
int a[ ]=new int[5];
a[5]=30/0;

.
} ac
catch(ArithmeticException e)
{
System.out.println("task1 is completed");
tu
}
catch(ArrayIndexOutOfBoundsException e)
{
.v

System.out.println("task 2 completed");
}
w

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


}
w

}
w

Nested try block


The try block within a try block is known as nested try block in java.
Why to use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
try
{
statement1;
statement2;
try
{
statement3;
statement4;
}
catch(Exception e)
{
//Code
}
}
catch(Exception e)
{
}
Example:
class Excep6
{

in
public static void main(String args[])
{
try

.
{ ac
try
{
System.out.println("going to divide");
tu
int b =39/0;
}
.v

catch(ArithmeticException e)
{
System.out.println(e);
w

}
try
w

{
int a[]=new int[5];
w

a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement);
}
catch(Exception e){System.out.println("handled");}

System.out.println("normal flow..");
}
}
Finally Block
 It 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 must be followed by try or catch block.
 For each try block there can be zero or more catch blocks, but only one finally block.
The finally block will not be executed if program exits (either by calling System.exit() or by
causing a fatal error that causes the process to abort).
Example 1: In the below example, divide by zero is not handled.
class TestFinallyBlock1
{
public static void main(String args[])
{
try

in
{
int data=25/0;

.
}
System.out.println(data); ac
catch(NullPointerException e)
tu
{
System.out.println(e);
.v

}
finally
w

{
System.out.println("finally block is always executed");
w

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

}
}
Output:
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestFinallyBlock1.main(TestFinallyBlock1.java:7)
Example 2: In the below example, Arithmetic exception is handled.
public class TestFinallyBlock2
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally

in
{
System.out.println("finally block is always executed");

.
} ac
System.out.println("rest of the code...");
}
}
tu
Output:
java.lang.ArithmeticException: / by zero
.v

finally block is always executed


rest of the code...
w

throw keyword
w

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


Syntax
w

throw exception;
In the below example, we have created the validate method that takes age as a parameter. If the age
is less than 35, we are throwing the ArithmeticException otherwise print a message You are
eligible.
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("Not Eligible to vote");
else
System.out.println("Eligible 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: You Are Failed
throws
 The Java throws keyword is used to declare an exception.
 The calling function must handle an exception thrown by called function.
 Using throws, we can declare
 unchecked Exception: under your control so correct your code.

in
 error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Example:

.
class Test1
{
ac
static void check() throws ArithmeticException
tu
{
System.out.println("Inside check function");
int a = 25 / 0;
.v

}
w

static void len() throws NullPointerException


{
String s = null;
w

System.out.println("Inside len function");


System.out.println(s.length());
w

throw new NullPointerException("Unknown String");


}

public static void main(String args[])


{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("Exception from main() caught ArithmeticException " +
e);
}
try
{
len();
}
catch(NullPointerException e)
{
System.out.println("Exception from main() caught NullPointerException " +
e);
}
System.out.println("Rest of the code");
}
}
Output:
Inside check function

in
Exception from main() caught ArithmeticException java.lang.ArithmeticException: / by zero
Inside len function

.
ac
Exception from main() caught NullPointerException java.lang.NullPointerException
Rest of the code
Difference between throw and throws in Java
tu
Sl. No. Throw Throws
.v

Java throw keyword is used to explicitly Java throws keyword is used to declare an
1
throw an exception. exception.
w

Checked exception cannot be propagated Checked exception can be propagated with


2
using throw only. throws.
w

3 Throw is followed by an instance. Throws is followed by class.


w

4 Throw is used within the method. Throws is used with the method signature.

You can declare multiple exceptions.


5 You cannot throw multiple exceptions. e.g. public void method() throws
IOException,SQLException.

void m()
void m() throws ArithmeticException
{
{
6 throw new ArithmeticException("sorry");
//method code
}
}
Finally
 The finally block always executes when the try block exits.
 This ensures that the finally block is executed even if an unexpected exception occurs.
 If exception is handled or not, finally block can be used.
Example:
class FinallyExample
{
public static void main(String[] args)
{
try
{
int x = 300/0;
}
catch(ArithmeticException e)

in
{
System.out.println("Caught " +e);

.
} ac
finally
{
System.out.println("finally block is executed");
tu
}
}
}
.v

Output:
Caught java.lang.ArithmeticException: / by zero
w

finally block is executed


w

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.
w

Abstract Class Interface

Abstract class can have abstract and non-abstract Interface can have only abstract methods.
methods.

Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.

Abstract class can have static methods, main Interface can't have static methods, main method
method and constructor. or constructor.
Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.

The abstract keyword is used to declare abstract The interface keyword is used to declare
class. interface.

Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

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, 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

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

.
 Java package provides access protection. ac
 Java package removes naming collision.
tu
.v
w
w
w

How to create Packages in Java?


 Choose appropriate name for the package.
 Use the keyword “package” followed by package name.
 Example: package mypack;
 First statement in the program should be package.
How to access package from another package?
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.*
 Ifwe use package.* then all the classes and interfaces of this package will be
accessible but not sub packages.
 The import keyword is used to make the classes and interface of another
package accessible to the current package.
Example:

/* First.java */
package first;

in
public class Message{
public void msg(){

.
ac
System.out.println("In Package “first”");
}
}
tu
/* Second.java */
package second;
.v

import first.*;
public class Display{
w

public static void main(String [] args){


Message m = new Message();
w

m.msg();
}
w

}
Output:
In Package “first”
2. import package.classname;
 In this case, particular class of package is imported.
 Only imported class has accessibility in the new program.
/* First.java */
package first;
public class Airtel{
public void Airtel(){
System.out.println("Airtel Function");}
}

public class Vodafone{


public void Vodafone(){
System.out.println("Vodafone Function");
}
}
public class Idea{
public void Idea(){
System.out.println("Idea Function");
}
}
/* Second.java */
package second;
import first.airtel; // Only airtel class is accessible

in
public class Display{
public static void main(String [] args){

.
Airtel a = new Airtel();

}
}
ac
Output:
tu
Airtel Function
3. Fully qualified name.
.v

 When fully qualified name is used then, importing package is not required.
 A class can be used by writing “packagename.class” in another program.
w

Example:
/* First.java */
w

package first;
public class Airtel{
public void Airtel(){
w

System.out.println("Airtel Function");}
}

public class Vodafone{


public void Vodafone(){
System.out.println("Vodafone Function");
}
}
public class Idea{
public void Idea(){
System.out.println("Idea Function");
}
}

/* Second.java */
package second;

public class Display{


public static void main(String [] args){
first.Airtel a = new first.Airtel();
first.Vodafone v = new first.Vodafone();
}
}
Output:
Airtel Function
Vodafone Function

. in
ac
tu
.v
w
w
w
4.

w
w
w
.v
tu
ac
. in

Вам также может понравиться