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

Unit-III, P2

This document covers the concepts of interfaces and packages in Java, explaining their features, syntax, and examples. It details how interfaces enable abstraction and multiple inheritance, and how packages organize classes and interfaces for better code management. Additionally, it discusses static imports and access modifiers for package classes, highlighting their importance in Java programming.

Uploaded by

KUSH SHARMA
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 views

Unit-III, P2

This document covers the concepts of interfaces and packages in Java, explaining their features, syntax, and examples. It details how interfaces enable abstraction and multiple inheritance, and how packages organize classes and interfaces for better code management. Additionally, it discusses static imports and access modifiers for package classes, highlighting their importance in Java programming.

Uploaded by

KUSH SHARMA
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/ 12

JAVA(UGCA-1932)

UNIT-III, PART-II

Course Code: UGCA1932 (PTU)


Course Name: Programming in Java
Course: BCA, Semester: 5th
UNIT-III, PART-II
Interface and Packages: Basics of interface, Multiple Interfaces, Multiple
Inheritance Using Interface, Multilevel Interface, Packages, Create and Access
Packages, Static Import and Package Class, Access Specifiers.

Basics of Interface:
The interface in Java is a mechanism to achieve abstraction. It is used to achieve abstraction and
multiple inheritances in Java. An interface in Java is a blueprint of a behavior. It is used to specify
the behavior of a class.
In Java, an interface is a reference type, similar to a class, that can contain abstract methods
(methods without a body) and constants (static final variables).

Key Features of Interfaces:

1. Abstract Methods: An interface can declare methods, that methods don't have bodies.
These methods are implicitly public and abstract.
2. Constants: Variables declared in an interface are implicitly public, static, and
final.
3. Multiple Inheritance: Java does not support multiple inheritance through classes, but a
class can implement multiple interfaces, allowing multiple inheritance of type.
4. Implements Keyword: A class uses the implements keyword to implement an
interface.

Syntax of an Interface:
interface MyInterface {
// Constant variable
int MY_CONSTANT = 10; // implicitly public, static, final

// Abstract method
void myMethod(); // implicitly public and abstract

// Default method (introduced in Java 8)


JAVA(UGCA-1932)
UNIT-III, PART-II

default void defaultMethod() {


System.out.println("This is a default method of interface.");
}

// Static method (introduced in Java 8)


static void staticMethod() {
System.out.println("This is a static method of interface.");
}
}

Example of an Interface:
// Define an interface
interface Animal {
// Abstract method
void sound(); // Every animal should implement this method

// Abstract method
void eat();
}

// Implementing the interface


class Dog implements Animal {
// Providing implementation for the sound method
public void sound() {
System.out.println("Barks");
}

// Providing implementation for the eat method


public void eat() {
System.out.println("Dog eats bones");
}
}

// Implementing the interface


class Cat implements Animal {
public void sound() {
System.out.println("Meows");
}

public void eat() {


System.out.println("Cat eats fish");
}
}

public class Main {


public static void main(String[] args) {
Animal dog = new Dog();
JAVA(UGCA-1932)
UNIT-III, PART-II

dog.sound(); // Outputs: Barks


dog.eat(); // Outputs: Dog eats bones

Animal cat = new Cat();


cat.sound(); // Outputs: Meows
cat.eat(); // Outputs: Cat eats fish
}
}

Key Points to be noticed in above program:

 Abstract Methods: The Animal interface declares abstract methods sound() and eat().
Classes Dog and Cat implement the interface and provide concrete implementations of these
methods.

 Implements Keyword: The Dog and Cat classes use the implements keyword to indicate
they are implementing the Animal interface.

Multiple Interfaces:
In Java, a class can implement multiple interfaces, which allows it to inherit behavior from multiple
interfaces. This is a form of multiple inheritance and is one of the key advantages of interfaces
in Java.

By using multiple interfaces, a class can implement methods from different interfaces. A class can
implement more than one interface by listing them after the implements keyword, separated by
commas.

Example of Multiple Interfaces:

interface Flyable {
void fly();
}

interface Swimmable {
void swim();
}

class Duck implements Flyable, Swimmable {


@Override
public void fly() {
System.out.println("Duck is flying");
}
JAVA(UGCA-1932)
UNIT-III, PART-II

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

public class Main {


public static void main(String[] args) {
Duck duck = new Duck();
duck.fly(); // Outputs: Duck is flying
duck.swim(); // Outputs: Duck is swimming
}
}

Note:
 The class Duck implements two interfaces: Flyable and Swimmable.

Multiple Inheritance in Java Using Interface:


Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes. But
we can use multiple inheritances in Java using Interface.
In Java, a class cannot inherit from more than one class (no multiple inheritance with classes), but
it can implement multiple interfaces. This enables Java to achieve a form of multiple inheritance
by combining behaviors from different interfaces.
JAVA(UGCA-1932)
UNIT-III, PART-II

Example:
// Interface 1
interface SHAHID {
// Default method
default void show()
{

// Print statement
System.out.println("It is from Default method.");
}
}

// Interface 2, Extending the above interface


interface Interface1 extends SHAHID {
// Abstract method
void display();
}

// Interface 3, Extending the above interface


interface Interface2 extends SHAHID {
// Abstract method
void print();
}

// Main class,Implementation class code


class TestClass implements Interface1, Interface2 {
// Overriding the abstract method from Interface1
public void display()
{
System.out.println("Display from Interface1");
}
// Overriding the abstract method from Interface2
public void print()
{
System.out.println("Print from Interface2");
}
// Main driver method
public static void main(String args[])
{
// Creating object of this class
// in main() method
TestClass obj = new TestClass();

// Now calling the methods from both the interfaces


JAVA(UGCA-1932)
UNIT-III, PART-II

obj.show(); // It is fromDefault method


obj.display(); //Display from Interface1
obj.print(); // Display from Interface2
}
}
OUTPUT

Multilevel Interfaces:
Multi-level interfaces in Java refer to a situation where one interface extends another interface.
This allows one interface to inherit the methods of another interface, creating a chain of
inheritance. The interface that extends another interface can add new methods or override existing
default methods.

Syntax:
interface ParentInterface {
void method1(); // Abstract method
}

interface ChildInterface extends ParentInterface {


void method2(); // Abstract method
}

class MyClass implements ChildInterface {


@Override
public void method1() {
System.out.println("Implementing method1");
}

@Override
public void method2() {
System.out.println("Implementing method2");
} }
JAVA(UGCA-1932)
UNIT-III, PART-II

Example of Multi-level Interfaces


// Base interface
interface Animal {
void eat();
}

// Extended interface
interface Animal2 extends Animal {
void walk();
}

// Another extended interface


interface Dog extends Animal2 {
void bark();
}

// Class implementing the most derived interface


class Dog2 implements Dog {
@Override
public void eat() {
System.out.println("Dog is eating");
}

@Override
public void walk() {
System.out.println("Dog is walking");
}

@Override
public void bark() {
System.out.println("Dog is barking");
}
}

public class Main {


public static void main(String[] args) {
Dog2 obj = new Dog2();
obj.eat(); // Outputs: Dog is eating
obj.walk(); // Outputs: Dog is walking
obj.bark(); // Outputs: Dog is barking
}
}

Explanation:
 Animal Interface: The base interface that defines the eat() method.
 Animal2 Interface: Extends the Animal interface and adds the walk() method.
 Dog Interface: Extends the Animal2 interface and adds the bark() method.
JAVA(UGCA-1932)
UNIT-III, PART-II

 Dod2 Class: Implements the Dog interface, so it must implement all the methods from the
entire chain of interfaces (eat(), walk(), and bark()).

Conclusion:

Multi-level interfaces are a powerful design tool in Java that enables interface inheritance. They
provide a clean and modular way to design a flexible and extensible system where common
behaviors can be defined in base interfaces and specialized behaviors can be added in extended
interfaces.

This approach is useful when you want to define common functionality in base interfaces and then
extend it in more specialized interfaces.

Packages in Java:
A set of classes and interfaces grouped together are known as Packages in JAVA. The name itself
defines that pack (group) of related types such as classes and interfaces. Every class is a part of a
certain package. When you need to use an existing class, you need to add the package within the
Java program.

In Java, packages are used to group related classes and interfaces, providing a modular and
organized structure for managing large codebases. They improve code maintainability and control
access to class and interfaces.

Features of Packages:

1. Organization: Packages organize related classes and interfaces into a hierarchical


structure.
2. Namespace Management: Packages prevent name conflicts by providing unique names.
3. Access Control: They allow control over classes and they are accessible outside of the
package using access modifiers.
4. Code Reusability: Packages can be reused in different projects, improving code
modularity.

Types of Packages:

1. Built-in Packages: These are provided by the Java API, such as java.util, java.io,
java.lang, etc.

Java provides a rich set of built-in packages, including:

 java.lang: Contains fundamental classes such as String, Math, Object, etc. It is


automatically imported into every Java program.
JAVA(UGCA-1932)
UNIT-III, PART-II

 java.util: Contains utility classes like ArrayList, HashMap, Date, and Collections.
 java.io: Contains classes for input and output operations, such as File, BufferedReader,
PrintWriter, etc.
 java.net: Provides classes for network operations like Socket, URL,
HttpURLConnection, etc.
 java.sql: Provides classes for database connectivity, such as Connection, Statement,
and ResultSet.

Importing/accessing Packages:

To use classes or interfaces from other packages, you can use the import keyword. Java
provides two ways to import packages:

1. Single Class Import: Import a specific class from a package.


2. Wildcard Import: Import all the classes from a package using the * symbol.

Syntax for Importing a Single Class:


import packageName.ClassName;

Syntax for Wildcard Import:


import packageName.*;

2. User-defined Packages: These are created by developers to organize their own classes
and interfaces. To create a user-defined package:

1. Choose a package name.


2. Declare the package at the top of your class file.
3. Store the class file in the same directory so that it can match the package name.

Creating a User-defined Package:

Step 1: Create a package.

package file.java.shapes;

public class Circle {


public void draw() {
System.out.println("Drawing a Circle");
}
}

Step 2: Store the file in the directory structure:


Store the Circle.java file in the file/java/shapes/ directory.
JAVA(UGCA-1932)
UNIT-III, PART-II

Step 3: Use the package in another class.

import file.java.shapes.Circle;

public class Main {


public static void main(String[] args) {
Circle circle = new Circle();
circle.draw(); // Outputs: Drawing a Circle
}
}

Conclusion:

Packages are a fundamental part of Java's structure, allowing for organized and maintainable code.
They help manage access control and provide a convenient way to reuse code across projects.
Java's built-in packages, along with user-defined packages, offer a robust way to manage large
applications effectively.

Static Import and Package Class:


In Java, static import and package class are advanced features that help developers access
classes, methods, and fields in a more convenient way. Let's break down each concept:

1. Static Import

The static import feature (introduced in Java 5) allows the static members (fields and
methods) of a class to be imported directly, so they can be accessed without the class name
prefix. This can make the code cleaner and more concise, especially when you have to use a lot
of static members from a particular class.

Syntax for Static Import:


import static packageName.ClassName.staticMemberName;
// For a single static member

import static packageName.ClassName.*;


// For all static members

Example of Static Import:

Without static import:

import java.lang.Math;
public class Main {
JAVA(UGCA-1932)
UNIT-III, PART-II

public static void main(String[] args) {


double result = Math.sqrt(25);
// Using Math class to call sqrt()with Math prefix
System.out.println(result); // Outputs: 5.0
}
}

With static import:

import static java.lang.Math.sqrt;

public class Main {


public static void main(String[] args) {
double result = sqrt(25);
// sqrt() method can be used directly without Math Prefix
System.out.println(result); // Outputs: 5.0
}
}

In this example, the sqrt() method from the Math class can be accessed directly without the
Math prefix because of the static import.

Importing All Static Members:

You can import all static members of a class using the * wildcard.

import static java.lang.Math.*;

public class Main {


public static void main(String[] args) {
double result1 = sqrt(25);
// Using sqrt() method directly
double result2 = pow(2, 3);
// Using pow() method directly
System.out.println(result1); // Outputs: 5.0
System.out.println(result2); // Outputs: 8.0
}
}

Here, both sqrt() and pow() methods are used without the Math class prefix, because of static
import.
JAVA(UGCA-1932)
UNIT-III, PART-II

2. Package Class

A package class refers to any class that belongs to a package. In Java, classes are grouped into
packages to organize and modularize the code. These package classes can be either built-in classes
from the Java API or user-defined classes that developers create within their own packages.

Example of Package Class:


package bbsbec.Shahid.utils; // Package declaration

public class Utility {


public void printMessage() {
System.out.println("This is a utility class");
}
}

Here, Utility is a package class that belongs to the bbsbec.Shahid.utils package. To


use this package class in another file, you can import it and then create an instance of it.

import bbsbec.Shahid.utils.Utility; // Import the package class

public class Main {


public static void main(String[] args) {
Utility util = new Utility();
// Create an instance of Utility
util.printMessage(); // Outputs: This is a utility class
}
}

Access Modifiers/Specifiers for Package class:

Java provides four levels of access control:

1. public: The class or member is accessible from any other class.


2. protected: The class or member is accessible within the same package and by subclasses.
3. default (no modifier): The class or member is accessible only within the same package.
4. private: The class or member is accessible only within the same class.

You might also like