KEMBAR78
Java Unit-3 | PDF | Class (Computer Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
7 views10 pages

Java Unit-3

The document explains the differences between abstract classes and interfaces in object-oriented programming, highlighting their structures and use cases. It details Java interfaces, their role in achieving multiple inheritance, and provides examples of implementing and extending interfaces. Additionally, it covers Java packages, their types, organization, and exception handling mechanisms, including the hierarchy of exceptions and keywords used for handling them.
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)
7 views10 pages

Java Unit-3

The document explains the differences between abstract classes and interfaces in object-oriented programming, highlighting their structures and use cases. It details Java interfaces, their role in achieving multiple inheritance, and provides examples of implementing and extending interfaces. Additionally, it covers Java packages, their types, organization, and exception handling mechanisms, including the hierarchy of exceptions and keywords used for handling them.
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/ 10

UNIT-3

Q1) Explain about the difference between Abstract Class and Interface
A)
In object-oriented programming, both abstract classes and interfaces define methods that must be
implemented by derived classes, but they have different purposes, structures, and use cases.
Here’s a breakdown of each:
1. Abstract Classes
Definition: An abstract class is a class that cannot be instantiated on its own; it serves as a
blueprint for other classes.
a) It can contain both fully implemented methods and abstract methods (methods without
implementations).
b) Subclasses inheriting from an abstract class must implement its abstract methods.
2. Interfaces
Definition : An interface is a contract that defines a set of methods a class must implement but
does not provide any implementation for these methods.
a) In most languages, interfaces cannot contain fields (state), but in some modern languages,
like Java 8+, they can include static and default methods.

Q2) Explain about Interfaces in Java


A)
Definition : In Java, an interface is a blueprint of a class that defines a set of methods that a class
must implement.
1) It's a pure abstract class, meaning all its methods are abstract and have no
implementation.
2) Interface is a collection of methods declaration and constants that one or more classes of
object will use
3) Interface is also a class it does not contain any declaration part that means it contains only
definition part
4) Java does not support the Concept of “Multiple Inheritance” Directly
5) With the help of Interfaces we can handle “Multiple Inheritance”
6) Basically Multiple Inheritance means that enables you to derive a subclass from more then
one parent class
7) For example A and B are Superclasses we derive class C from both

The Java Compiler Show error when we declare a program like this to fulfill “Multiple Inheritance”
class C extends A extends B // error
{
}
8) The above statement is invalid and Multiple Inheritance is not possible in Java that is
classes in Java cannot have more than one Super Class.
9) But Java Provides alternate approach called “Interface”
10) Java Supports “Multiple Interfaces” to Support “Multiple Inheritance”
11) But it also needs a “Class”
12) Here interfaces are accessed by using keyword called “implements”
13) It also Supports “Hybrid Inheritance”

Syntax:
interface interfacename
{
Declaration of variables , Constants and methods
}
class classname implements interfacename
{
}

Accessing Implementation through Interface References:


1. In Java, when a class implements an interface, you can use a reference variable of the
interface type to hold an instance of the implementing class.
2. This allows you to access the methods defined in the interface, even though the actual
object might be of a different class.
interface Animal
{
void makeSound();
}

class Dog implements Animal


{
public void makeSound()
{
System.out.println("Woof!");
}
}

class Cat implements Animal


{
public void makeSound()
{
System.out.println("Meow!");
}
}
class sksd
{
public static void main(String[] args)
{
Animal myDog = new Dog(); // Animal reference to a Dog object
Animal myCat = new Cat(); // Animal reference to a Cat object

myDog.makeSound(); // Outputs: Woof!


myCat.makeSound(); // Outputs: Meow!
}
}
Ex: To achieve “Multiple Inheritance”
interface A
{
public void display1();//Declaration of Method only
}
interface B
{
public void display2();//Declartion of Method only
}
class C implements A,B// Here in Class "C" we use the properties of "A,B"
{
public void display1()
{
System.out.println("I am the Property of A");
}
public void display2()
{
System.out.println("I am the Property of B");
}
public void display3()
{
System.out.println("I am the Property of C");
}

}
class mul
{
public static void main(String args[])
{
C obj=new C();
obj.display1();
obj.display2();
obj.display3();
}
}
Extending Interfaces:
1. One interface is also extended by another interface
2. One Interface can inherit another by use of keyword “extends”
3. This is much like “inheriting class”
Ex:
interface one
{
void print1();
void print2();
}
interface two extends one
{
void print3();
}
class three implements two
{
public void print1()
{
System.out.println("I am One");
}
public void print2()
{
System.out.println("I am two");
}
public void print3()
{
System.out.println("I am three");
}
}
class test
{
public static void main(String args[])
{
three obj=new three();
obj.print1();
obj.print2();
obj.print3();
}
}

Q3) Explain about Packages in Java


A)
Definition : In Java, a package is a way of grouping related classes and interfaces together. It
serves as a container for classes, interfaces, enumerations, and sub-packages, helping to organize
code and prevent naming conflicts.

Types of Packages in Java


Java packages can be broadly categorized into two types:
1. Built-in Packages:
o Java provides a set of standard libraries organized into packages. Examples include:
 java.lang: Contains fundamental classes like String, Math, and System.
 java.util: Contains utility classes like ArrayList, HashMap, and Date.
 java.io: Contains classes for input and output operations like File,
InputStream, and OutputStream.
2. User-defined Packages:
o Developers can create custom packages to organize their own classes and
interfaces.
Key Points about Packages in Java
1. Organization:
o Packages help organize classes logically. For example, all utility classes could be
placed in a util package, and all GUI-related classes in a gui package.
2. Avoid Naming Conflicts:
o By placing classes in different packages, developers avoid conflicts between classes
that have the same name but different purposes.
3. Access Control:
o Packages provide a way to control access to classes and methods. Using public and
protected access modifiers, developers can restrict access to certain parts of the
codebase.
4. Reusability:
o Code in packages can be easily reused by importing them into other projects or
parts of a project.
5. Hierarchical Structure:
o Java allows packages to be hierarchical. For example, java.util is a package that
contains various utility classes like ArrayList, and java.util.concurrent is a
subpackage specifically for concurrency utilities.
Creating and Accessing a Package:
To create a package, use the package keyword as the very first statement in a Java file. For
example, let’s create a package called myPackage and define a class called Message in it.

Step-by-Step Example
1. Create a folder structure that matches the package name
// Package declaration
package myPackage;
public class Message
{
public void showMessage()
{
System.out.println("Hello from myPackage!");
}
}
In this example, Message is part of the myPackage package.
2. Compile the Package which is in mypackage Foloder
3. Type the following command (class path)
javac -d . myPackage/Message.java
3. Accessing and importing the Package
1. Now that the package and its compiled class are ready, create a new Java file to use the
Message class from myPackage.
Importing the package:
 “import” is a special keyword which is used to access the properties of already created
Built- in Package or User-Defined Pacakge
import myPackage.*;
class sksd
{
public static void main(String args[ ])
{
Message obj = new Message();
obj.showMessage();
}
}
Now it access the properties showMessage( ) from the class Message which is already
defined in “myPackage” package

Q4) Explain about Exception Handling in java


A)
Definition: Exception handling is a mechanism in Java to handle runtime errors or exceptions that
may occur during the execution of a program. It helps in making the program more robust and
preventing it from crashing unexpectedly.

Key Concepts:

1. Exception: An exception is an event that occurs during the execution of a program that
disrupts the normal flow of the program.
2. Exception Handling: The process of intercepting and handling exceptions to prevent
program crashes.

Exception Hierarchy in Java

Java exceptions are divided into several categories based on the class hierarchy. The base class for
all exceptions is java.lang.Throwable, which has two primary subclasses:

A) Error:

o The Error class represents serious issues that typically cannot be handled by a Java
program, such as memory overflows or JVM issues.

Types of Errors

There are primarily three types of errors in Java:

a) Syntax Error b) Logical Error c) Run-time Errors

1. Syntax Errors:

 These occur when the code violates the grammatical rules of the Java language.
 They are detected by the compiler during compilation.
 Examples: missing semicolons, mismatched brackets, misspelled keywords, etc.
 Solution: Correct the syntax errors as indicated by the compiler.

2. Runtime Errors (Exceptions):

 These occur during the execution of the program.


 They are caused by factors like invalid input, resource constraints, or system errors.
 They are not detected by the compiler.
 Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException,
etc.
 Solution: Use try-catch blocks to handle exceptions gracefully.

3. Logical Errors:
 These occur when the program runs without crashing but produces incorrect results.
 They are caused by flaws in the program's logic or algorithm.
 They are the most difficult to detect and fix.
 Solution: Careful code review, testing, and debugging are essential to identify and fix
logical errors.

B) Exception(Built in Exceptions)

o The Exception class represents conditions that a program might want to catch. This
class has two main subclasses:

1. Checked Exceptions These exceptions must be either handled or declared in the method
signature using the throws keyword. The compiler enforces their handling.

 IOException: Thrown when an I/O operation fails.


 ClassNotFoundException: Thrown when a class cannot be found.
 SQLException: Thrown when a database operation fails.
 FileNotFoundException: Thrown when a file cannot be found.
 InterruptedException: Thrown when a thread is interrupted.

2. Unchecked Exceptions (Runtime Exceptions) These exceptions are not checked at compile time
and may occur at runtime. While it's recommended to handle them, the compiler doesn't enforce
it.

 NullPointerException: Thrown when trying to use a null reference.


 ArrayIndexOutOfBoundsException: Thrown when trying to access an array element with an
invalid index.
 ArithmeticException: Thrown when an arithmetic operation fails, such as division by zero.
 IllegalArgumentException: Thrown when an illegal argument is passed to a method.
 ClassCastException: Thrown when trying to cast an object to an incompatible type.

Ex:

//Wap on Built in Exception

class ExceptionExample
{
public static void main(String[] args)
{
try
{
int result = 10 / 0; // Will throw ArithmeticException
}
catch (ArithmeticException e)
{
System.out.println(e);
}
}
}

Exception Handling Keywords in Java

Java provides several keywords to handle exceptions:

1. try:
o The try block contains code that may throw an exception.
o If an exception occurs within the try block, the subsequent code in the try block is
skipped, and control transfers to the catch block.
2. catch:
o The catch block handles the exception.
o It takes a parameter representing the exception type to be caught.
o Multiple catch blocks can follow a single try block to handle different types of
exceptions.
3. finally:
o The finally block contains code that will always execute, regardless of whether an
exception was thrown or not.
o This block is often used to release resources like file streams or database
connections.
4. throw:
The throw keyword is used to explicitly throw an exception, either a custom
o
exception or one of the standard exceptions.
5. throws:
o The throws keyword is used in a method signature to declare that a method might
throw specific exceptions. This is often used with checked exceptions

Rethrowing Exception

 Adding Additional Context: You may want to add more information to the
exception message or log details before rethrowing it.
Syntax:

try
{
// Code that might throw an exception
}
catch (ExceptionType e)
{
throw e; // Rethrow the caught exception
}

Example:

class RethrowExample
{
public static void divideNumbers(int a, int b)
{
try
{
int result = a / b;
System.out.println("Result: " + result);
}
catch (ArithmeticException e)
{
System.err.println("Logging: Division by zero attempted");
throw e; // Rethrow the exception to be handled by the caller
}
}
public static void main(String[] args)
{
try
{
divideNumbers(10, 0);
}
catch (ArithmeticException e)
{
System.out.println("Exception caught in main: " + e.getMessage());
}
}
}

You might also like