0% found this document useful (0 votes)
8 views36 pages

Lec_12

The document explains the concept of packages and interfaces in Java, detailing their structure, advantages, and usage. It covers built-in and user-defined packages, methods for accessing packages, and the role of interfaces in achieving abstraction and multiple inheritance. Additionally, it discusses enhancements introduced in Java 8, such as default and static methods in interfaces, which improve code reusability and backward compatibility.

Uploaded by

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

Lec_12

The document explains the concept of packages and interfaces in Java, detailing their structure, advantages, and usage. It covers built-in and user-defined packages, methods for accessing packages, and the role of interfaces in achieving abstraction and multiple inheritance. Additionally, it discusses enhancements introduced in Java 8, such as default and static methods in interfaces, which improve code reusability and backward compatibility.

Uploaded by

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

Packages and Interface

Packages
• A package in Java is used to group related classes.
Think of it as a folder in a file directory. 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)
• There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.
• Advantage of Java Package
• 1) Java package is used to categorize the classes and interfaces so that they
can be easily maintained.
• 2) Java package provides access protection.
• 3) Java package removes naming collision.

• 1. 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.
• 2. User-defined Packages
• These are the packages that are defined by the user.
• 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, use the package keyword:

package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
• Save the file as MyPackageClass.java, and compile it:
• javac -d . MyPackageClass.java

• This forces the compiler to create the "mypack" package.


• The -d keyword specifies the destination for where to
save the class file.
• The package name should be written in lower case to
avoid conflict with class names.
• When we compiled the package in the example above, a
new folder was created, called "mypack".

• To run the MyPackageClass.java file, write the following:


• java mypack.MyPackageClass
• How to access package from another package?
• There are three ways to access the package from
outside the package.
• import package.*;
• import package.classname;
• fully qualified name.

• 1) Using packagename.*
• If you use package.* then all the classes and interfaces
of this package will be accessible but not subpackages.
• The import keyword is used to make the classes and
interface of another package accessible to the current
package.
• Example –
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
• Now first compile A.java –
• javac -d . A.java
• Compile B.java –
• javac -d . B.java
• Now run the B class file –
• java mypack.B

• 2) Using packagename.classname
• If you import package.classname then only
declared class of this package will be
accessible.
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
• 3) Using fully qualified name
• If you use fully qualified name then only
declared class of this package will be
accessible. Now there is no need to import.
But you need to use fully qualified name every
time when you are accessing the class or
interface.
• It is generally used when two packages have
same class name e.g. java.util and java.sql
packages contain Date class.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
• If you import a package, all the classes and interface of that package will
be imported excluding the classes and interfaces of the subpackages.
Hence, you need to import the subpackage as well.
• Subpackage in java
• Package inside the package is called the subpackage. It should
be created to categorize the package further.
• Let's take an example, Sun Microsystem has definded a
package named java that contains many classes like System,
String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for
Input/Output operation, Socket and ServerSocket classes are
for networking etc and so on. So, Sun has subcategorized the
java package into subpackages such as lang, net, io etc. and
put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.
• The standard of defining package is domain.company.package
e.g. com.chitkara.bean or org.sssit.dao.
• Example –
package com.chitkara.core;
class Demo{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
• Compile it - java com.chitkara.core.Demo
• Run it - java com.chitkara.core.Demo
• Static Import in Java –
• In Java, static import (import static) allows us to import static members
(methods and variables) of a class directly, so we don't need to prefix
them with the class name.

• 1. Without Static Import (Normal Way)

import java.lang.*; // optional as this is by default imported

public class Main {


public static void main(String[] args) {
System.out.println(Math.sqrt(16)); // Using Math class name
System.out.println(Math.PI); // Using Math class name
}
}
• 2. With Static Import –
import static java.lang.Math.sqrt; // Importing static method
import static java.lang.Math.PI; // Importing static variable

public class Main {


public static void main(String[] args) {
System.out.println(sqrt(16)); // Using Math class name
System.out.println(PI); // Using Math class name
}
}
• 3. Importing All Static Members
• Instead of importing specific members, we can import all
static members of a class using:

import static java.lang.Math.*; // Importing all static members

public class Main {


public static void main(String[] args) {
System.out.println(sqrt(16)); // Using Math class name
System.out.println(PI); // Using Math class name
}
}
• 4. Using Static Import with User-Defined
Classes –
package mypackage;

public class Utility {


public static void greet() {
System.out.println("Hello from Utility
class!");
}
}
import static mypackage.Test.*; // Importing all static member fron Test

public class Test {


public static void main(String[] args) {
greet(); // Directly calling greet() without Utility.greet()
}
}

• When to Use Static Import?


• ✔ When frequently using static members from a class.
✔ When improving code readability.
• ❌ Avoid overusing static import, as it can make code less readable if
multiple classes have the same method names.
Interface
• In Java, an interface is a blueprint of a class that contains only
abstract methods (before Java 8) and static/final variables. It is
used for achieving abstraction and multiple inheritance in Java

• Key Characteristics of Interfaces


• Only method declarations (No implementation before Java 8).
• All methods are public and abstract by default.
• Only static and final variables are allowed.
• A class implements an interface using the implements keyword.
• Supports multiple inheritance (A class can implement multiple
interfaces).
• Example –

// Define an interface
interface Animal {
void makeSound(); // Abstract method (public & abstract by default)
}

// Implementing the interface in a class


class Dog implements Animal {
public void makeSound() { // Must provide method definition
System.out.println("Dog barks: Woof Woof!");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Dog dog = new Dog(); // Creating object of implementing class
dog.makeSound();
}
}
• Interface with Multiple Implementing Classes
• An interface can be implemented by multiple classes.

interface Vehicle {
void start();
}

// Class implementing Vehicle interface


class Car implements Vehicle {
public void start() {
System.out.println("Car starts with a key.");
}
}

// Another class implementing the same interface


class Bike implements Vehicle {
public void start() {
System.out.println("Bike starts with a self-start button.");
}
}

public class MultipleImplementation {


public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start();

Vehicle myBike = new Bike();


myBike.start();
}
}
• Interface Supporting Multiple Inheritance –

• Unlike classes, Java does not support multiple inheritance with classes but allows multiple inheritance
with interfaces.

• Example –
interface Printable {
void print();
}

interface Showable {
void show();
}

// A class implementing multiple interfaces


class Document implements Printable, Showable {
public void print() {
System.out.println("Printing document...");
}

public void show() {


System.out.println("Showing document preview...");
}
}
public class MultipleInheritanceExample {
public static void main(String[] args) {
Document doc = new Document();
doc.print();
doc.show();
}
}
• Interface with Default and Static Methods
(Java 8+) -
• Before Java 8, interfaces could only have
abstract methods, but from Java 8 onwards,
they can have:
• Default methods (with implementation)
• Static methods (with implementation
• Example –
interface MyInterface {
void show(); // Abstract method

// Default method with implementation


default void display() {
System.out.println("This is a default method in the interface.");
}

// Static method with implementation


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

// Implementing the interface


class MyClass implements MyInterface {
public void show() {
System.out.println("Implementing abstract method.");
}
}

public class InterfaceWithDefaultStatic {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.show();
obj.display(); // Calling default method

MyInterface.staticMethod(); // Calling static method (directly from interface)


}
}
• Interface Variables (Final & Static) -
• All variables in an interface are implicitly public, static, and
final.

interface Constants {
int MAX_VALUE = 100; // Implicitly public, static, and final
}

public class InterfaceVariableExample {


public static void main(String[] args) {
System.out.println("Max Value: " + Constants.MAX_VALUE);
// Constants.MAX_VALUE = 200; // ERROR: Cannot change
final variable
}
}
• When to Use an Interface?
• ✔ When multiple classes need to share a
common behavior but have different
implementations.
✔ When achieving multiple inheritance is
necessary.
✔ When designing loosely coupled systems
(decoupling implementations from interfaces).
• Why Did Java 8 Allow Method Bodies in
Interfaces? 🤔
• Before Java 8, interfaces in Java could only
have abstract methods, meaning they could
not have method implementations. However,
Java 8 introduced default and static methods
with method bodies in interfaces. This change
was made to ensure backward compatibility
and enhance flexibility in interface design.
• . Backward Compatibility (Avoiding API Breakage)
• 🔸Before Java 8, adding a new method to an interface broke all implementing
classes because they would have to provide an implementation for the new
method.
• 🔸 Solution in Java 8:
• Default methods allow interface designers to add new methods without
breaking existing implementations.

interface Vehicle {
void start();
}

// Suppose we add a new method


interface Vehicle {
void start();
void stop(); // This breaks all implementing classes!
}
• All existing classes implementing Vehicle would break!
• Solution –
interface Vehicle {
void start(); // Abstract method

// New default method added without breaking


existing classes
default void stop() {
System.out.println("Vehicle stopping...");
}
}
• Now, existing classes will continue to work, as
they are not forced to override stop().
• Allowing Code Reusability in Interfaces -
• Before Java 8, common functionality had to be implemented in each class separately.
• Now, with default methods, the common functionality can be written once in the interface and
reused.
• Example: Without Default Methods (Before Java 8)

interface Printer {
void print();
}

class InkjetPrinter implements Printer {


public void print() {
System.out.println("Printing using Inkjet Printer...");
}
}

class LaserPrinter implements Printer {


public void print() {
System.out.println("Printing using Laser Printer...");
}
}

// If we want a new feature like duplex printing, we must implement it in each class.
• Each class must implement duplicate code separately.
• With Java 8 Default Methods (Code Reusability) –
interface Printer {
void print();

// Default method for duplex printing


default void duplexPrint() {
System.out.println("Printing on both sides...");
}
}

class InkjetPrinter implements Printer {


public void print() {
System.out.println("Printing using Inkjet Printer...");
}
}

class LaserPrinter implements Printer {


public void print() {
System.out.println("Printing using Laser Printer...");
}
}

public class DefaultMethodExample {


public static void main(String[] args) {
Printer inkjet = new InkjetPrinter();
inkjet.print();
inkjet.duplexPrint(); // Using default method without overriding

Printer laser = new LaserPrinter();


laser.print();
laser.duplexPrint();
}
}
• Allowing Utility Methods in Interfaces (static
methods) -
• Before Java 8, utility methods (helper
functions) had to be placed in separate utility
classes like Collections or Arrays.
• Now, static methods in interfaces allow utility
functions to be directly placed inside
interfaces.
• Example: Static Method in Interface
interface MathOperations {
static int add(int a, int b) { // Static method in interface
return a + b;
}
}

public class StaticMethodExample {


public static void main(String[] args) {
System.out.println(MathOperations.add(5, 3)); // Calling
static method
}
}
• No need for a separate utility class!

You might also like