Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
16 views14 pages

Unit Iii

This document provides an overview of interfaces and packages in Java, detailing the differences between abstract classes and interfaces, as well as how to declare and implement them. It also covers the concept of packages, including built-in and user-defined packages, and explains how to set the classpath and import packages. Additionally, the document discusses exception handling, its benefits, types of exceptions, and the distinction between checked and unchecked exceptions.
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)
16 views14 pages

Unit Iii

This document provides an overview of interfaces and packages in Java, detailing the differences between abstract classes and interfaces, as well as how to declare and implement them. It also covers the concept of packages, including built-in and user-defined packages, and explains how to set the classpath and import packages. Additionally, the document discusses exception handling, its benefits, types of exceptions, and the distinction between checked and unchecked exceptions.
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/ 14

UNIT-III

 INTERFACES:
Abstract Class: An abstract class is a class that cannot be instantiated on its own and is
designed to be inherited by other classes.
Interface: An interface is a contract specifying a set of methods that must be implemented by
any class that implements it.
Abstract class Interface

1) Abstract class can have abstract and non- 1) Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static methods also.

2) Abstract class doesn't support multiple


2) Interface supports multiple inheritance.
inheritance.

3) Abstract class can have final, non-final, static


3) Interface has only static and final variables.
and non-static variables.

4) Abstract class can provide the 4) Interface can't provide the implementation of
implementation of interface. abstract class.

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

6) An abstract class can extend another Java 6) An interface can extend another Java interface
class and implement multiple Java interfaces. only.

7) An abstract class can be extended using 7) An interface can be implemented using


keyword "extends". keyword "implements".

8) A Java abstract class can have class members 8) Members of a Java interface are public by
like private, protected, etc. default.

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

 Define an Interface:
 How to declare and implement the interface:
Definition:
An interface is a abstract contract that specifies a set of methods, constants, and events that
must be implemented by any class that implements it.
Characteristics:
1. Abstract: Interfaces cannot be instantiated and have no implementation.
2. Multiple Inheritance: A class can implement multiple interfaces.
3. Methods: Interfaces declare abstract methods (without implementation) and default
methods (with implementation).
4. Constants: Interfaces can define public, static, and final constants.
5. Events: Interfaces can define events (in languages like C#).

1
Declaring Interfaces:
Syntax for Java Interfaces:
public interface InterfaceName {
// methods
void methodName1();
int methodName2(int parameter);

// constants
String CONSTANT_NAME = "value";
}

Implementing Interfaces:
A class implements an interface using the implements keyword:
// create an interface
interface Language
{
void getName(String name);
}
// class implements interface
class ProgrammingLanguage implements Language {
// implementation of abstract method
public void getName(String name) {
System.out.println("Programming Language: " + name);
}}
class Main {
public static void main (String[] args) {
ProgrammingLanguage language = new ProgrammingLanguage ();
language. getName("Java");
}}
Benefits:
1. Abstraction: Interfaces hide implementation details.
2. Polymorphism: Interfaces enable method overriding.
3. Loose Coupling: Interfaces reduce class dependencies.
4. Testability: Interfaces facilitate unit testing.

2
By understanding interfaces theoretically, developers can effectively apply them in practice to create

robust, maintainable, and scalable software systems.


Accessing implementations through interface reference:
We can declare variables as object references that use an interface rather than a class.
Any instance 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 process is similar to using a superclass reference to access a subclass object.

The following example calls the callback() method via an interface reference variable
s interface Callback
{
void callback(int param);
}
class Client implements Callback
{
// Implement Callback's interface
public void callback (int p)
{
System.out.println("callback called with " + p);
}
void aa ()
{
System.out.println("hi.");
}
}
public class Main
{
public static void main (String [] args)
{
Callback c = new Client ();
c.callback (42);
}
}
OUTPUT:
callback called with 42
tThe variable c is declared to be of the interface type Callback, yet it was assigned an instance
of Client.
Although c can be used to access the callback () method, it cannot access any other members of
the Client class.
An interface reference variable has knowledge only of the methods declared by
its interface declaration.
Thus, c could not be used to access aa () since it is defined by Client but not Callback.
Extending Interface:
An interface extends another interface:
In object-oriented programming, an interface can extend another interface, allowing it to inherit and
build upon the methods and constants defined in the parent interface.
Syntax:
public interface ChildInterface extends ParentInterface
{

3
// methods and constants
}
Example:
// Parent interface
public interface Printable {
void print();}

// Child interface extending parent


public interface AdvancedPrintable extends Printable {
void printInColor();
void printInBlackAndWhite();
}
// Implementation class implementing child interface
public class AdvancedPrinter implements AdvancedPrintable {
@Override
public void print() {
System.out.println("Printing...");
}
@Override
public void printInColor() {
System.out.println("Printing in color...");
}
@Override
public void printInBlackAndWhite() {
System.out.println("Printing in black and white...");
}
}
Key points:
1. Child interface inherits print() from Printable.
2. Child interface adds printInColor() and printInBlackAndWhite().
3. Implementation class must implement all methods from both interfaces.

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.
syntax:
package <packagename>;
public class A{
public void msg()
{
-----
-----
}

4
Types of packages:

Built-in Packages:
These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:
java.lang: Contains language support classes(e.g classes which defines primitive data types, math
operations). This package is automatically imported.
java.io: Contains classes for supporting input / output operations.
java.util: Contains utility classes which implement data structures like Linked List, Dictionary and
support ; for Date / Time operations.
java.applet: Contains classes for creating Applets.
java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc). 6)
java.net: Contain classes for supporting networking operations.
User-defined packages:
These are the packages that are defined by the user. First we create a directory myPackage (name
should be same as the name of the package). Then create the MyClass inside the directory with
the first statement being the package names.
Creating and accessing a package:
In Java, a package is a namespace that organizes related classes, interfaces, and other types. Here's a
step-by-step guide on creating and accessing a package in Java:
Creating a Package:
1. Choose a unique package name (e.g., com.example.mypackage).
2. Create a directory with the package name (e.g., com/example/mypackage).
3. Inside the directory, create your Java classes, interfaces, or other types.
4. Use the package statement at the top of each Java file to specify the package name.
Example:
// File: com/example/mypackage/MyClass.java
package com.example.mypackage;
public class MyClass {
// Class code here
}
Accessing a Package:
1. Import the package using the import statement.
2. Use the fully qualified name (package + class name) to access classes or members.
Example:
// File: Main.java
import com.example.mypackage.MyClass; // Import package
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass(); // Access class
// Use obj
}
}

5
Key Points:
Package names are typically in lowercase and use reverse domain notation (e.g.,
com.example.mypackage).
Package directories must match the package name.
Use the import statement to avoid using fully qualified names.
You can also use import package.* to import all classes within a package.

Common Commands:
- javac -d : Compile Java files and create package directories.
- java -cp : Run Java programs with package imports.

 CLASSPATH
How to Set Classpath in Java?
CLASSPATH describes the location where all the required files are available which are used in the
application. Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate the
required files. If the CLASSPATH is not set, Java Compiler will not be able to find the required files
and hence will throw the following error.
Error: Could not find or load main class <class name> (e.g. GFG)
The above error is resolved when CLASSPATH is set.
Java
// If the following code is run when the CLASSPATH is not
// set, it will throw the above error.

// If it is set, we get the desired result

import java.io.*;

class GFG {
public static void main(String[] args)
{
// prints GeeksForGeeks to the console
System.out.println("GeekForGeeks!");
}
}

Output
GeekForGeeks!

Set the CLASSPATH in JAVA in Windows


Command Prompt:
Open the Command Prompt.
Use the following command to set the CLASSPATH:
set CLASSPATH=.;C:\path\to\your\classes;C:\path\to\your\libraries
Note: The dot (.) represents the current directory, and the semicolon (;) is used as a separator
between different paths.
Example:
set CLASSPATH=.;C:\Users\GFG\JavaClasses;C:\Program Files\Java\libs
GUI:
1. Select Start
2. Go to the Control Panel

6
3. Select System and Security

4.Select Advanced System settings

7
5. Click on Environment Variables

6. Click on New under System Variables

8
7.Add CLASSPATH as variable name and path of files as a variable value.

8.Select OK.

 IMPORTING PACKAGES:
In Java, you import packages using the import statement at the beginning of your Java source file,
before any class definitions.
Here's the basic syntax:
import package.name.*;
or
import package.name.ClassName;
Importing All Classes in a Package
To import all classes in a package, use the asterisk (*) wildcard:
import java.util.*;
This imports all classes and interfaces in the java.util package.
Importing a Specific Class
To import a specific class, specify the class name:
import java.util.ArrayList;
Importing Static Members
To import static members (methods and variables) of a class, use the static keyword:
import static java.lang.Math.PI;
import static java.lang.Math.pow;
Best Practices
- Import only what you need to avoid naming conflicts.
- Avoid importing classes with the same name from different packages.
- Use your IDE's auto-import feature or organize imports regularly.
Example Use Case
Suppose you want to use the ArrayList class in your Java program:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
System.out.println(list);
}
}
In this example, we import java.util.ArrayList to use its functionality in our program.

9
 EXCEPTION HANDLING:
 Benefits of Exception Handling:
Exception handling in Java provides several benefits, including:

1. Prevents Program Termination: Exception handling prevents the program from


terminating abruptly when an error occurs, allowing it to continue executing and
providing a better user experience.

2. Error Identification and Diagnosis: Exceptions provide valuable information


about the error, such as the type of exception, error message, and location, making it
easier to identify and diagnose the issue.

3. Improved Code Reliability: Exception handling ensures that resources, such as


files, connections, and memory, are properly closed and released, even if an exception
occurs.

4. Enhanced Code Robustness: By handling exceptions, you can anticipate and


manage potential errors, making your code more robust and resilient.

5. Better Error Messaging: Customized exception messages provide clear and


concise information about the error, facilitating easier debugging and troubleshooting.

6. Separation of Concerns: Exception handling separates error-handling logic from


the main program logic, making the code more organized and maintainable.

7. Reduced Debugging Time: Exception handling reduces debugging time by


providing specific information about the error and its location.

8. Improved Security: Proper exception handling can prevent sensitive information,


such as database credentials, from being exposed in error messages.

9. Compliance with Coding Standards: Exception handling is a best practice in Java


programming, ensuring compliance with coding standards and guidelines.

10. Enhanced User Experience: By handling exceptions, you can provide a more
informative and user-friendly error experience, rather than displaying technical error
messages.

 The Classification of Exceptions:


OR
Types of Exception in Java
In Java, exception is an event that occurs during the execution of a program and
disrupts the normal flow of the program's instructions. Bugs or errors that we don't
want and restrict our program's normal execution of code are referred to
as exceptions. In this section, we will focus on the types of exceptions in Java and
the differences between the two.
Exceptions can be categorized into two ways:
1. Built-in Exceptions
o Checked Exception
o Unchecked Exception

10
2. User-Defined Exceptions

Built-in Exception:
Exceptions that are already available in Java libraries are referred to as built-in
exception. These exceptions are able to define the error situation so that we can
understand the reason of getting this error. It can be categorized into two broad
categories, i.e., checked exceptions and unchecked exception.
User-defined Exception:
In addition to the built-in exceptions, Java allows you to define your own custom
exceptions. User-defined exceptions are created by extending the base Exception class
or its subclasses. By creating customized exceptions, you can handle application-
specific exceptional conditions that are not covered by the built-in exceptions. They
are handled using keywords like try, catch, finally, throw, and throws.
Exception Hierarchy
All exception and error types are subclasses of the class Throwable, which is the base
class of the hierarchy. One branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch. NullPointerException is an
example of such an exception. Another branch, Error is used by the Java run-time
system(JVM) to indicate errors having to do with the run-time environment itself
(JRE). StackOverflowError is an example of such an error.

11
 Checked and Unchecked Exceptions:( Built-in Exceptions)

Checked or (Compile-Time) Exceptions:


A checked exception is an exception that is checked 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 these exceptions.
List of Checked exceptions:
1.ClassNotFoundException: It is thrown when the Java Virtual Machine (JVM) tries to load
the particular class and the specified class cannot be found in the classpath.
2.InterruptedException: It is thrown when a thread is waiting, sleeping, or otherwise
occupied, and the thread is interrupted, either before or during the activity.
3.IOException: Input/Output exceptions(I/O), and they occur whenever an input or output
operation is failed or interpreted.
4.InstallationException: It is thrown when an application tries to create an instance of a
class using newInstance method in class Class, but the specified class object cannot be
instantiated because it is an interface or is an abstract class.
5.SQLException: The SQLException class and its subtypes provide information about
errors and warnings that occur while a data source is being accessed.
6.FileNotFoundException: FileNotFoundException which is a common exception which
occurs while we try to access a file. FileNotFoundExcetion is thrown by constructors
RandomAccessFile, FileInputStream, and FileOutputStream.
UnChecked or (Run-Time) Exceptions: An unchecked exception is an exception that
occurs at the time of execution. These are also called as Run-Time exceptions. These include
programming bugs, such as errors or improper use of an API. Run-Time exceptions are
ignored at the time of compilation.
List of Unchecked exceptions:
1.ArithematicException: Arithmetic Exception Thrown when an exceptional arithmetic
condition has occurred. For example, an integer "divide by zero" throws an instance of this
class.
2.ClassCastException: This exception thrown to indicate that the code has attempted to cast an
object to a subclass of which it is not an instance.
So, for example, when one tries to cast an Integer to a String, String is not a subclass
of Integer, so a ClassCastException will be thrown.
3.NullPointerException: NullPointerException is a RuntimeException. In Java, a special
null value can be assigned to an object reference. NullPointerException is thrown when
program attempts to use an object reference that has the null value. These can be:

12
4.ArrayIndexOutOfBoundsException: The ArrayIndexOutOfBoundsException occurs
whenever we are trying to access any item of an array at an index which is not present in the
array. In other words, the index may be negative or exceed the size of an array.
5.ArryStoreException: ArrayStoreException in Java occurs whenever an attempt is made to
store the wrong type of object into an array of objects. The ArrayStoreException is a class
which extends RuntimeException, which means that it is an exception thrown at the runtime.
6.IllegalThreadStateException: When a threadis already running and executing its
functions inside the run() method and amidst its execution, a call to the same thread,leads to
an IllegalThreadStateException.

 Try, Catch, Finally In Java:


The below keywords are used in Java for Exception handling.
 Try
 Catch
 Finally
 Throw
 Throws
The following table briefly describes these keywords
Keyword Description
Try We specify the block of code that might give rise to the exception in a special block with a “Try”
keyword.

The general syntax of the try block is as follows:


try{
//set of statements that can raise exception
}
Catch When the exception is raised it needs to be caught by the program. This is done using a “catch”
keyword. So a catch block follows the try block that raises an exception. The keyword catch should
always be used with a try.
The general syntax of the catch block is:
catch (Exception e){
//code to handle exception e
}

Finally Sometimes we have an important code in our program that needs to be executed irrespective of
whether or not the exception is thrown. This code is placed in a special block starting with the
“Finally” keyword. The Finally block follows the Try-catch block.
try {
// Code that may throw an exception
s}
catch (Exception e) {
// Exception handling code
...
}
finally {
// Cleanup code
// This block will always execute, regardless of whether an exception occurred or not
...
}
Throw The keyword “throw” is used to throw the exception explicitly.

13
The throw keyword in Java is used to explicitly throw an exception from a method or any block of
code. We can throw either checked or unchecked exception. The throw keyword is mainly used to
throw custom exceptions.
Syntax in Java throw
throw Instance

Example:
throw new ArithmeticException("/ by zero");
Throws The keyword “Throws” does not throw an exception but is used to declare exceptions. This keyword
is used to indicate that an exception might occur in the program or method.
throws is a keyword in Java that is used in the signature of a method to indicate that this method
might throw one of the listed type exceptions. The caller to these methods has to handle the
exception using a try-catch block.
Syntax of Java throws
type method_name(parameters) throws exception_list

exception_list is a comma separated list of all the


exceptions which a method might throw.
Catching Multiple Exceptions
As already mentioned, a try block can contain a code that raises more than one exception. In
this case, we will need more than one catch block to handle each exception. A single try
block can be followed by multiple catch blocks. Each catch block will handle the independent
exceptions.
In the case of multiple catch blocks, we have to remember the below points:
 In a Java program, at any instance of time, only one exception can occur. Also, at any
point, only one catch block is executed.
 The multiple catch blocks should be ordered in such a way that the catch block for
most specific exceptions should come first and then the general.
Nested Try-Catch
A try block inside another try block is called a nested try block. We need such structures in
certain situations when a piece of code contained in a try code may be such that some lines
raise certain exceptions and another piece of code raises a completely different exception.
The general syntax of a nested try block is given below:
try {
//try_block 1;
try {
//try_block 2;
}
catch(Exception e)
{
//exception handler code
} }
catch(Exception e)
{
//exception handler code
}

14

You might also like