You are on page 1of 54

Abstract class in Java

◾A class which is declared with the abstract keyword is


known as an abstract class in Java.

◾ It can have abstract and non-abstract methods


(method with the body).
What is Abstraction in Java?
• Abstraction is a process of hiding the implementation details
and showing only functionality to the user.
• Another way, it shows only essential things to the user and
hides the internal details, for example, sending SMS where
you type the text and send the message. You don't know the
internal processing about the message delivery.
• Abstraction lets you focus on what the object does instead of
how it does it.
What are the ways to achieve Abstraction

◾ There are two ways to achieve abstraction in java

▪ Abstract class

▪ Interface
Abstract class in Java

◾A class which is declared as abstract is known as an abstract


class. It can have abstract and non- abstract methods. It needs to be
extended and its method implemented. It cannot be instantiated.
◾ Points to Remember
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the
body of the method.
Example of abstract class
Abstract Method in Java

A method which is declared as abstract and does not have implementation is


known as an abstract method.

Example of abstract method


Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its implementation
is provided by the Honda class.
Understanding the real scenario of Abstract class

• In this example, shape is an abstract class, and its implementation is provided by


Rectangle and Circle class

• Mostly, we don't know about the implementation class (which is hidden to the
end user), and an object of the implementation class is provided by the
factory method.
Understanding the real scenario of Abstract class
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.
Another example of Abstract class in java
Abstract class having constructor, data member and methods
An abstract class can have a data member, abstract method, method body (non- abstract method),
constructor, and even main() method.
• If there is an abstract method in a class, that class must be abstract.

• If you are extending an abstract class that has an abstract method, you must either provide the
implementation of the method or make this class abstract.
Interface in Java
• An interface in java is a blueprint of a class.
• It has static constants and abstract methods.
• The interface in Java is a mechanism to achieve abstraction.
• There can be only abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
• In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
• Since Java 8, we can have default and static methods in an interface.
• Since Java 9, we can have private methods in an interface.
Why use Java interface?

◾ There 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.
How to declare an interface?
An interface is declared by using the interface keyword.

It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default.

A class that implements an interface must implement all the methods declared in the interface.

Syntax:
Java 8 Interface Improvement

◾ Since
Java 8, interface can have default and static
methods.
Internal addition by the compiler

The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static
and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods are public and abstract.
The 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.
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.
Java Interface Example: Drawable

• In this example, the Drawable interface


has only one method.
• Its implementation is provided by
Rectangle and Circle classes. In a real
scenario, an interface is defined by
someone else, but its implementation is
provided by different implementation
providers.
• Moreover, it is used by someone else.
The implementation part is hidden by the
user who uses the interface.
Java Interface Example: Bank

Let's see another example of java interface


which provides the implementation of Bank
interface.
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces,


it is known as multiple inheritance.
Multiple inheritance in Java by interface
Multiple inheritance is not supported through class in java, but it is possible by an interface,
why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of
ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its
implementation is provided by the implementation class. For example:

As you can see in this


example, Printable and
Showable interface have
same methods but its
implementation is provided
by class TestTnterface1, so
there is no ambiguity.
Interface inheritance
A class implements an interface, but one interface extends another interface.
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method. Let's
see an example:
Java 8 Static Method in Interface
Since Java 8, we can have static method in interface. Let's see an example:
What is marker or tagged interface?

◾ An interface which has no member is known as a marker or


tagged interface, for example, Serializable, Cloneable,
Remote, etc. They are used to provide some essential
information to the JVM so that JVM may perform some
useful operation.
Nested Interface in Java

◾ Note: An interface can have another


interface which is known as a nested
interface. We will learn it in detail in the
nested classes chapter. For example:
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.

◾ Simply, abstract class achieves partial abstraction (0 to


100%) whereas interface achieves fully abstraction (100%).

◾ But there are many differences between abstract class and


interface.
Difference between abstract class and interface
abstract class interface
1. Abstract class can have abstract and non-abstract methods 1. Interface can have only abstract methods. Since java 8, it
can have default and static method also
2. Abstract class does not support multiple inheritance 2. Interface supports multiple inheritance
3. Abstract class can have final, non-final, static and non- 3. Interface only have static and final variables
static variables
4. The abstract keyword is used to declare abstract class 4. The interface keyword is used to declare interface
5. An abstract class can extend another java class and 5. An interface can extend another java interface only
implement multiple java interfaces
6. An abstract class can be extended using “extend” keyword 6. An java interface can be implement using “implements”
keyword.
7. An abstract class can have class members like private and 7. Members of java interface is public by default.
protected
8. Example: 8. Example:
public abstract class shape public interface Drawable
{ {
abstract void draw(); void draw();
} }
Exception Handing
• 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.
• In Java, an exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at runtime.
• An exception is a problem that arises during the execution of a program. When
an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended,
therefore, these exceptions are to be handled.
• Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException,
DevidebyZero, ArrayOutofBound, etc.
What is exception

• An exception can occur for many different reasons. Following are


some scenarios where an exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of
communications or the JVM has run out of memory.
Hierarchy of Java Exception classes
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses:
Exception and Error. A hierarchy of Java Exception classes are given below:
Types of Java Exceptions
• There are mainly two types of exceptions: checked and unchecked.
Here, an error is considered as the unchecked exception. According to
Oracle, there are three types of exceptions:
• Checked Exception
• Unchecked Exception
• Error
Checked Exception
• Checked exceptions − A checked exception is an exception that is
checked (notified) by the compiler at compilation-time, these are also
called as compile time exceptions.
• These exceptions cannot simply be ignored, the programmer should
take care of (handle) these exceptions.
Example of Checked Exception
• For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler
prompts the programmer to handle the exception.
Unchecked Exception

• Unchecked exceptions − An unchecked exception is an exception that


occurs at the time of execution.
• These are also called as Runtime Exceptions.
• These include programming bugs, such as logic errors or improper use
of an API.
• Runtime exceptions are ignored at the time of compilation.
Example of Unchecked exception
• For example, if you have declared an array of size 4 in your program,
and trying to call the 5th element of the array then
an ArrayIndexOutOfBoundsException occurs.
Checked vs. Unchecked exceptions
• Checked Exception
• The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc.
• Checked exceptions are checked at compile-time
• Unchecked Exception
• The classes which inherit RuntimeException are known as unchecked exceptions
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
• Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
Java Exception Keyword
Keyword Description

try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally. It
means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed by
finally block later.
finally The "finally" block is used to execute the important code of the program. It
is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method. It is
always used with method signature.
Try- Catch Block
• The code which is leads to exceptions is placed in the try block. When
an exception occurs, that exception occurred is handled by catch
block associated with it.
• Every try block should be immediately followed either by a catch
block or finally block.
• A catch statement involves declaring the type of exception you are
trying to catch. If an exception occurs in protected code, the catch
block (or blocks) that follows the try is checked.
• If the type of exception that occurred is listed in a catch block, the
exception is passed to the catch block much as an argument is passed
into a method parameter.
Java exception example
import java.util.Scanner;
class JavaException
{
public static void main(String args[])
{
int a,b,c;
Scanner s= new Scanner(System.in); OUTPUT:
System.out.println("enter value of a");
a = s.nextInt(); java.lang.ArithmeticException: / by zero
System.out.println("enter value of b");
b = s.nextInt();
try
{
c = a/b;
} catch (ArithmeticException e)
{
System.out.println(e);
}
}
}
Multiple Catch Blocks
• A try block can be followed by multiple catch blocks. The multiple catch blocks looks like the
following −
public class MultipleCatchBlock1 {
public static void main(String args[]) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{ OUTPUT:
System.out.println("Parent Exception occurs");
} Arithmetic Exception occurs
System.out.println("rest of the code"); rest of the code
}
}
Throw / Throws Keyword
• If a method does not handle a checked exception, the method must
declare it using the throws keyword. The throws keyword appears at
the end of a method's signature.

• You can throw an exception, either a newly instantiated one or an


exception that you just caught, by using the throw keyword.

• The difference between throws and throw keywords, throws is used


to postpone the handling of a checked exception and throw is used to
invoke an exception explicitly.
Example of Throw / Throws
• A method can declare that it throws more than one exception, in
which case the exceptions are declared in a list separated by commas.
For example, the following method declares that it throws a
RemoteException and an InsufficientFundsException
The Finally Block

• The finally block follows a try block or a catch block. A finally block of
code always executes, irrespective of occurrence of an Exception.

• Using a finally block allows you to run any cleanup-type statements


that you want to execute, no matter what happens in the protected
code.
Example of Finally Block
Common Scenario of Java Exception
There are some scenarios where unchecked exceptions may occur. They are as
follows:
1. A scenario where Arithmetic Exception occur
If we divide a number by 0, there occurs an Arithmetic Exception
int a = 50/0; //Arithmetic exception

2. A scenario where Null Pointer Exception occur


If we have a NULL value in any variable, performing any operation on the variable
throws a Null Pointer Exception.
String s = null;
System.out.println(“s.length() ”); //NullPointerException
Common Scenario of Java Exception
3) A scenario where Number Format Exception occur
The wrong formatting of any value may occur Number Format Exception.
Suppose, we have a String variable that have characters, converting this variable into digit will occur
NumberFormatException.
String s = “abc”;
int a = Integer.parseInt(s); //Number Format Exception

4) A scenario where Array Index Out of Bounds Exception Occur


If we are inserting any value in the wrong index, it will result in ArrayIndexOutOfBounds Exception
as shown below.
int a[] = new int[5];
a[6] = 100; // ArrayIndexOutOfBoundsException
User defined exception
• You can create your own exceptions in Java. Keep the
following points in mind when writing your own exception
classes −
• All exceptions must be a child of Throwable.
• If you want to write a checked exception that is
automatically enforced by the Handle or Declare Rule, you
need to extend the Exception class.
• If you want to write a runtime exception, you need to
extend the RuntimeException class.
Creating user defined exception

• You just need to extend the predefined Exception class to create your
own Exception. These are considered to be checked exceptions.
Let's see a simple example of Java custom exception. In the following code, constructor of InvalidAgeException takes a string as an argument. This string is
passed to constructor of parent class Exception using the super() method. Also the constructor of Exception class can be called without using a parameter
and calling super() method is not mandatory.
// main method
// class representing custom exception public static void main(String args[])
class InvalidAgeException extends Exception {
{ try
public InvalidAgeException (String str) {
{ // calling the method
// calling the constructor of parent Exception validate(13);
super(str); }
} } catch (InvalidAgeException ex)
// class that uses custom exception InvalidAgeException {
public class TestCustomException1 System.out.println("Caught the exception");
{
// method to check the age // printing the message from InvalidAgeException object
static void validate (int age) throws InvalidAgeException{ System.out.println("Exception occured: " + ex);
if(age < 18){ }
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid to vote"); System.out.println("rest of the code...");
} }
else { }
System.out.println("welcome to vote");
}
}

You might also like