0% found this document useful (0 votes)
2 views

Module-3

Uploaded by

subhani.shaik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module-3

Uploaded by

subhani.shaik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Module-3

Packages and Interfaces


Packages in Java
A package is a namespace that organizes a set of related classes and interfaces. It helps in
avoiding name conflicts and can control access with protected and default access levels.
 Purpose: Organize related classes and interfaces into a single unit for better
modularity and maintainability.
Syntax:
package com.example.utilities;
Example:
package com.example.utilities;
public class Utility {
public void performTask() {
System.out.println("Task performed.");
}
}
Key Features:
 Provides a unique namespace for the types it contains.
 Controls access with protected and default access levels.
 Facilitates the creation of modular programs.
Interfaces in Java
An interface is a reference type in Java, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces cannot
contain instance fields.
 Purpose: Define a contract that classes can implement, specifying methods without
implementing them.
Syntax:
public interface Drawable {
void draw();
}
Example:
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() {
System.out.println("Drawing a circle.");
}
}
Key Features:
 Methods are implicitly public and abstract (except static and default methods).
 Supports multiple inheritance, as a class can implement multiple interfaces.
 From Java 8 onwards, interfaces can have default and static methods with
implementations.

Key Differences Between Packages and Interfaces

Interface
An interface is declared using the interface keyword and typically contains method signatures
without implementations. Since Java 8, interfaces can also include default and static methods
with implementations.
Example
public interface Animal {
void eat(); // Abstract method
void sleep(); // Abstract method
default void run() { // Default method
System.out.println("Running...");
}
static void breathe() { // Static method
System.out.println("Breathing...");
}
}
Implementing an Interface
A class implements an interface using the implements keyword and provides concrete
implementations for all abstract methods.

public class Dog implements Animal {


@Override
public void eat() {
System.out.println("Dog is eating.");
}
@Override
public void sleep() {
System.out.println("Dog is sleeping.");
}
}
In the above example, the Dog class implements the Animal interface, providing concrete
implementations for the eat and sleep methods.

Multiple Inheritance with Interfaces


Java does not support multiple inheritance with classes, but a class can implement multiple
interfaces, allowing it to inherit behaviors from multiple sources.
Example
interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}

public class Duck implements Flyable, Swimmable {


@Override
public void fly() {
System.out.println("Duck is flying.");
}

@Override
public void swim() {
System.out.println("Duck is swimming.");
}
}
Here, the Duck class implements both Flyable and Swimmable interfaces, providing
implementations for both fly and swim methods.
Types of Interfaces
1. Functional Interface: An interface with exactly one abstract method. Used primarily
with lambda expressions.
Syntax
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
2. Marker Interface: An interface with no methods or fields. Used to mark a class for a
specific behavior.
Syntax
interface Serializable {}

Key Characteristics
 Abstraction: Interfaces allow you to define methods that must be implemented,
hiding the implementation details.
 Multiple Inheritance: A class can implement multiple interfaces, allowing for
multiple inheritance of types.
 Polymorphism: Interfaces enable objects to be treated as instances of their interface
rather than their actual class.
 Default and Static Methods: Since Java 8, interfaces can have default and static
methods with implementations.
 Private Methods: Since Java 9, interfaces can have private methods to encapsulate
code used by default methods.
Interfaces Vs abstract classes
In Java, both interfaces and abstract classes are tools for achieving abstraction, but they
serve different purposes and have distinct characteristics. Here's a comprehensive comparison
to help you understand their differences and decide when to use each:

Key Differences Between Interfaces and Abstract Classes

Feature Interface Abstract Class


Only abstract methods (until Java 7); from
Can have both abstract and
Method Types Java 8, can have default and static methods;
concrete methods.
from Java 9, can have private methods.
Can have final, non-final,
Variables Only static and final variables (constants). static, and non-static
variables.
Multiple A class can extend only one
A class can implement multiple interfaces.
Inheritance abstract class.
Constructors Cannot have constructors. Can have constructors.
Access Methods are implicitly public; cannot have Can have public, protected,
Modifiers other access modifiers. and private methods.
Can extend one class and
Inheritance Can extend multiple interfaces. implement multiple
interfaces.
Instantiation Cannot be instantiated. Cannot be instantiated.
Provides a common base
Defines a contract for classes to implement;
Use Case with shared code; ideal for
ideal for unrelated classes sharing behavior.
related classes.
When to Use Interfaces
Consider using interfaces when:
 You need to define a contract that multiple classes can implement, regardless of their
position in the class hierarchy.
 You require multiple inheritance of type, as Java allows a class to implement multiple
interfaces.
 You aim for complete abstraction without any implementation details.
When to Use Abstract Classes
Consider using abstract classes when:
 You have a base class that should provide common code to multiple related classes.
 You need to define non-static or non-final fields to maintain the state of an object.
 You want to provide default implementations for some methods, while leaving others
abstract.
Inner classes
In Java, inner classes are classes defined within another class. They are used to logically
group classes that are only used in one place, enhancing encapsulation and readability. Inner
classes have access to the members (including private members) of the outer class.

Types of Inner Classes in Java


1. Member Inner Class (Non-static Nested Class)
o Defined at the member level of a class (outside any method).
o Has access to all members (including private) of the outer class.
o Requires an instance of the outer class to instantiate.
Example:
class Outer {
private int x = 10;
class Inner {
void display() {
System.out.println("x = " + x);
}
}
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display(); // Outputs: x = 10
}
}
2. Static Nested Class
 Declared with the static modifier.
 Can access static members of the outer class.
 Does not require an instance of the outer class to instantiate.
Example:
class Outer {
private static int x = 10;
static class Inner {
void display() {
System.out.println("x = " + x);
}
}
public static void main(String[] args) {
Outer.Inner inner = new Outer.Inner();
inner.display(); // Outputs: x = 10
}
}
3. Local Inner Class
 Defined within a method or a block.
 Can access final or effectively final variables of the enclosing scope.
Example:
class Outer {
void outerMethod() {
int y = 20;
class Inner {
void display() {
System.out.println("y = " + y);
}
}
Inner inner = new Inner();
inner.display(); // Outputs: y = 20
}
public static void main(String[] args) {
Outer outer = new Outer();
outer.outerMethod();
}
}
4. Anonymous Inner Class
 A class without a name and for which only a single object is created.
 Used to instantiate classes that may be subclassed or implement interfaces.
Example:
abstract class Animal {
abstract void makeSound();
}
public class Main {
public static void main(String[] args) {
Animal dog = new Animal() {
void makeSound() {
System.out.println("Bark");
}
};
dog.makeSound(); // Outputs: Bark
}
}
Inner classes in Java offer several advantages that enhance code organization, encapsulation,
and maintainability. Here's an overview of their key uses:
1. Enhanced Encapsulation and Information Hiding
Inner classes allow you to encapsulate helper classes within their enclosing classes, hiding
implementation details from the outside world. This promotes a cleaner API and prevents
unintended access or modification.
2. Logical Grouping and Improved Code Organization
By placing classes that are only relevant to their enclosing classes inside them, inner classes
help in logically grouping related code. This enhances readability and makes the codebase
more maintainable.
3. Simplified Access to Outer Class Members
Non-static inner classes have access to all members of their outer classes, including private
ones. This tight coupling facilitates seamless interaction between the inner and outer classes.
4. Efficient Event Handling in GUI Applications
Inner classes, especially anonymous ones, are commonly used to implement event listeners in
GUI applications. They provide a concise way to handle events, keeping the event-handling
code close to the component that generates the event.

5. Implementation of Callback Mechanisms


Inner classes are useful for implementing callbacks, allowing for flexible and reusable code
structures. They enable the definition of behavior that can be passed around and invoked at a
later time.
6. Designing Complex Data Structures
When implementing data structures like linked lists or trees, inner classes can represent the
nodes or elements, encapsulating their behavior and keeping related code together.
7. Improved Security Through Restricted Access
By defining inner classes as private, you can restrict their visibility to the enclosing class,
enhancing security and preventing unauthorized access.
Extending Interfaces
An interface can extend one or more interfaces using the extends keyword. This means the
subinterface inherits all the abstract methods of its superinterfaces.
Example:
interface A {
void method1();
void method2();
}
interface B extends A {
void method3();
}
class MyClass implements B {
public void method1() {
System.out.println("Method 1");
}
public void method2() {
System.out.println("Method 2");
}
public void method3() {
System.out.println("Method 3");
}
}
In this example, interface B extends interface A, so it inherits method1() and method2(). The
class MyClass implements interface B and thus must provide implementations for all three
methods.
Multiple Inheritance with Interfaces
Java allows an interface to extend multiple interfaces, enabling a form of multiple
inheritance.
Example:
interface X {
void methodX();
}

interface Y {
void methodY();
}
interface Z extends X, Y {
void methodZ();
}
class MyClass implements Z {
public void methodX() {
System.out.println("Method X");
}
public void methodY() {
System.out.println("Method Y");
}
public void methodZ() {
System.out.println("Method Z");
}
}
Handling Method Conflicts
When multiple interfaces being extended have methods with the same signature, and at least
one provides a default implementation, the compiler requires the implementing class to
override the method to resolve the conflict.
interface A {
default void greet() {
System.out.println("Hello from A");
}
}
interface B {
default void greet() {
System.out.println("Hello from B");
}
}
class MyClass implements A, B {
public void greet() {
A.super.greet(); // or B.super.greet();
}
}
In this scenario, MyClass must override the greet() method to resolve the ambiguity between
interfaces A and B.

You might also like