Java_Module4_demo
Java_Module4_demo
2
Java Access modifiers
•In Java, the access specifiers (also known as access modifiers) used to control or
restrict the scope or accessibility of a
• class,
• constructor,
• variable,
• method or data member of class and interface.
•There are four access specifiers, and their list is below.
• default (or) no modifier
• public
• protected
• Private
http://www.btechsmartclass.com/java/java-access-specifiers.html
5
Java Access modifiers
The private members can be accessed only inside the same class.
The protected members are accessible to every child class (same package or
other packages).
The default members are accessible within the same package but not outside
the package.
6
Java Access modifiers
•In java, the accessibility of the members of a class or interface depends on its
access specifiers.
•The following table provides information about the visibility of both data
members and methods.
7
Java Access modifiers
•In java, we cannot employ all
access specifiers on everything.
•The following table describes
where we can apply the access
specifiers.
8
Packages
•Packages are containers for classes. They are used to keep
the class name space compartmentalized.
•A package in Java is used to group related classes.
•Packages are stored in a hierarchical manner and are
explicitly imported into new class definitions.
•We use packages to avoid name conflicts, and to write a
better maintainable code.
•For example, a package allows you to create a class
named List, which you can store in your own package
without concern that it will collide with some other class
named List stored elsewhere.
•Packages are divided into two categories.
9
Packages
•A set of classes and interfaces grouped together
are known as Packages.
•We use packages to avoid name conflicts, and to write
a better maintainable code.
•The benefits of using Packages in Java are as follows.
• The packages organize the group of classes into a single API unit
• It will control the naming conflicts
• The access protection will be easier. Protected and default are the
access level control to the package.
• Easy to locate the related classes
• Reuse the existing classes in packages
10
Packages
• A set of classes and interfaces grouped together are known as Packages.
• We use packages to avoid name conflicts, and to write a better
maintainable code.
• Packages are divided into two categories.
• Built-in Packages (packages from the Java API)
• User-defined Packages (create your own packages)
11
Packages
12
Packages
13
Packages Example Scanner class
• There are many packages to
choose from. In the previous
example, we used the
Scanner class from the
java.util package.
• This package also contains
date and time facilities,
random- number generator
and other utility classes.
• To import a whole package,
end the sentence with an
asterisk sign (*). The
following example will
import ALL the classes in
the java.util package:
14
Packages Example Scanner class
15
Packages 3 Ways to import Packages
•Import One Specific Class From a Package
• import java.util.Scanner
• In the above píogíam, you have included only one scanneí
class fíom util subpackage.
16
Packages User Defined Packages
17
Packages Example Using Static import
18
Packages User Defined Packages
• To create your own package, you need to
understand that Java uses a file system directory to
store them. Just like folders on your computer:
• 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.
19
Packages User Defined Packages
• 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;
20
Packages User Defined Packages
• Finding Packages and CLASSPATH
•As just explained, packages are typically mirrored by directories.
•This raises an important question: How does the Java run-
time system know where to look for packages that you create?
22
Default Access Specifier in Java: Usage in Class
23
Packages User Defined Packages – Example- 4
24
Packages User Defined Packages – Example- 5
25
Abstract Class
•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).
•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.
26
Abstract Class
•There are two ways to achieve abstraction in java
• Abstract class (0 to 100%)
• Interface (100%)
27
Abstract Class Simple example
28
Abstract Class Real use-case example
•In this example, Shape is the abstract class, and its implementation is provided
by the Rectangle and Circle classes.
•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.
•A factory method is a method that returns the instance of the class. We will
learn about the factory method later.
•In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
29
Abstract Class Real use-case example -1
30
Abstract Class Real use-case example -1
31
Abstract Class example Real use-case example -2
Interface in
•The
Java 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.
•it cannot be instantiated just like the abstract class.
33
Interface in Java Example-1
•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.
34
Interface in Java Example-1
35
Interface in Java Example-1
36
Interface example Example-2
37
Interface example Example-2
38
Interface Default Methods
• Like regular interface methods, default methods are implicitly public;
there’s no need to specify the public modifier.
• Unlike regular interface methods, we declare them with the default
keyword at the beginning of the method signature, and they provide
an implementation.
• In a typical design based on abstractions, where an interface has one
or multiple implementations, if one or more methods are added to the
interface, all the implementations will be forced to implement them
too. Otherwise, the design will just break down.
• Default interface methods are an efficient way to deal with this issue.
They allow us to add new methods to an interface that are
automatically available in the implementations. Therefore, we don’t
need to modify the implementing classes.
• To better understand the functionality of default interface methods,
let’s create a simple example.
• Interfaces can have static methods as well, similar to static methods in
classes.
39
• Default methods were introduced to provide backward compatibility
for old interfaces so that they can have new methods without affecting
existing code.
49
Interface Default Methods -Example-1
50
Interface Default Methods -Why it is required?
• Please notice how the default methods,
turnAlarmOn() and turnAlarmOff(), from our Vehicle
interface are automatically available in the Car class.
• Furthermore, if at some point we decide to add
more default methods to the Vehicle interface, the
application will still continue working, and we won’t
have to force the class to provide implementations
for the new methods.
• The most common use of interface default methods
is to incrementally provide additional functionality
to a given type without breaking down the
implementing classes.
41
Multiple inheritance in Java by
interface
Java Abstract Vs
Interface
• Abstract class and interface
both are used to achieve
abstraction where we can
declare the abstract methods.
43
Exception Handling in Java
• The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application
can be maintained.
• Dictionary Meaning: Exception is an abnormal condition.
• In Java, an exception is an event that disrupts the normal flow of the
program.
• It is an object which is thrown at runtime.
• Exception Handling is a mechanism to handle runtime errors such as
ArithmeticException, ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
44
Advantage of Exception Handling
•The core advantage of exception handling is to maintain
the normal flow of the application.
•An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions.
Let's consider a scenario:
•Suppose there are 10 statements in a Java program and
an exception occurs at statement 5;
•the rest of the code will not be executed, i.e.,
statements 6 to 10 will not be executed.
•However, when we perform exception handling, the
rest of the statements will be executed.
•That is why we use exception handling in Java.
45
Types of Java
Exceptions
Checked Exception
• These are the exceptions that are checked at
compile time.
• For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
Unchecked Exception
• The classes that inherit the RuntimeException are
known as unchecked exceptions. For example,
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.
• Unchecked exceptions are not checked at compile-
time, but they are checked at runtime.
Error
• Error is irrecoverable. Some example of errors
are OutOfMemoryError, VirtualMachineError,
AssertionError etc.
46
Types of Java
Exceptions
•Java Exception Keywords
Keyword Description
try The "try" keyword is used to specify a block where we should place an
exception code.
It means we can't use try block alone. The try block must be followed
by either catch or finally.
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 necessary code of the
program. It is executed whether an exception is handled or not.
48
Common Scenarios of Java Exceptions
•There are given some scenarios where unchecked exceptions may occur. They
are as follows:
•A scenario where ArithmeticException occurs
• If we divide any number by zero, there occurs an ArithmeticException.
• int a=50/0;//ArithmeticException
49
Java Exceptions
Index
• Java Exceptions Index
• Java Try-Catch Block
• Java Multiple Catch Block
• Java Nested Try
• Java Finally Block
• Java Throw Keyword
• Java Exception Propagation
• Java Throws Keyword
• Java Throw vs Throws
• Java Final vs Finally vs Finalize
• Java Exception Handling with Method Overriding
• Java Custom Exceptions
https://www.javatpoint.com/exception-handling-in-java
50
Internal Working of Java try-catch block
51
Internal Working of Java try-catch
blockJVM firstly checks whether the exception is handled or not. If exception is
•The
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 the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
52
Internal Working of Java try-catch
block try to understand the
•Let's
problem if we don't use a try-
catch block.
•Output:
• Exception in thread "main"
java.lang.ArithmeticException: /
by zero
53
Internal Working of Java try-catch
block by exception handling
•Solution
54
Internal Working of Java try-catch
block the exception using the
•handle
parent class exception.
55
Java Multi-catch block
•A try block can be followed by
one or more catch blocks.
•Each catch block must contain a
different exception handler.
•So, if you have to perform
different tasks at the
occurrence of different
exceptions, use java multi-catch
block.
56
Java Multi-catch block - Example
•All catch blocks must be ordered from most specific to most general,
i.e. catch for ArithmeticExcepti on must come before catch
for Exception.
57
Java Multi-catch block - Example
• In this example, we generate
NullPointerException, but
didn't provide the
corresponding exception
type.
• In such case, the catch block
containing the parent
exception class Exception
will invoked.
58
Java finally
•block
Java finallyblock is
always executed whether
an exception is handled
or not.
• Therefore, it contains all
the necessary
statements that need to
be printed regardless of
the exception occurs or
not.
• finally block in Java can
be used to put "cleanup"
code such as closing a
file, closing connection,
etc.
• The important statements
59
Java finally
block
to be printed can be
placed in the finally block.
51
0
Java finally block – Example - Case 1: When an exception does not occur
• Let's see the
below example
where the Java
program does
not throw
any
exception, and
the finally block
is executed
after the try
block.
60
Java finally block – Example - Case 2: When an exception occurr but not handled by
the catch block
• Let's see the below
example where
the Java program
does not throw
any exception, and
the finally block is
executed after the
try block.
61
Java Exceptions Handing
https://www.javatpoint.com/exception-handling-in-java
•
62