0% found this document useful (0 votes)
42 views19 pages

MODULE-03 (Interfaces and Packages)

Uploaded by

mca.bca.2024
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)
42 views19 pages

MODULE-03 (Interfaces and Packages)

Uploaded by

mca.bca.2024
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/ 19

OOPs with Java Programming 22MCA22

MODULE-03
INTERFACES AND PACKAGES: Interface: Interfaces VS Abstract classes, defining an interface,
implement interfaces, accessing implementations through interface references, extending interface;
Packages: Defining, creating and accessing a package, understanding CLASSPATH, importing
packages.

INTERFACE:-

 An interface in Java is a blueprint of a class. It has static constants and abstract methods.
 The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.
 In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
 Java Interface also represents the IS-A relationship.
 It cannot be instantiated just like the abstract class.
 Since Java 8, we can have default and static methods in an interface.
 Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final
by default. A class that implements an interface must implement all the methods declared in the
interface.
Syntax:
Interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

Example: interface printable


{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[]) {
A6 obj = new A6();
obj.print();
}
} OUTPUT: Hello

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

Interfaces VS Abstract classes:


Interfaces Abstract classes
1) Interface can have only abstract methods. 1) Abstract class can have abstract and non-
Since Java 8, it can have default and static abstract methods.
methods also.
2) Interface supports multiple inheritance. 2) Abstract class doesn't support multiple
inheritance
3) Interface has only static and final variables. 3) Abstract class can have final, non-final,
static and non-static variables.
4) Interface can't provide the implementation 4) Abstract class can provide the
of abstract class. implementation of interface.
5) The interface keyword is used to declare 5) The abstract keyword is used to declare
interface. abstract class.
6) An interface can extend another Java 6) An abstract class can extend another Java
interface only. class and implement multiple Java interfaces.
7) An interface can be implemented using 7) An abstract class can be extended using
keyword "implements". keyword "extends".
8) Members of a Java interface are public by 8) A Java abstract class can have class members
default. like private, protected, etc.
Example: Example:
public interface Drawable{ public abstract class Shape
void draw(); {
} public abstract void draw();
}

Example of abstract class and interface in Java:


//Creating interface that has 4 methods
interface A
{
void a(); //bydefault, public and abstract
void b();
void c();
void d();
}

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A
{
public void c(){System.out.println("I am C");
}
}

//Creating subclass of abstract class, now we need to provide the implementation of rest of the methods
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}

//Creating a test class that calls the methods of A interface


class Test5
{
public static void main(String args[])
{
A a=new M();
a.a();
a.b();
a.c();
a.d();
}
}
OUTPUT: I am a
I am b
I am c
I am d

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as


multiple inheritance.

Example: interface Printable

void print();

interface Showable

void show();

class A7 implements Printable,Showable

public void print()

System.out.println("Hello");

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

public void show()

System.out.println("Welcome");

public static void main(String args[])

A7 obj = new A7();

obj.print();

obj.show();

OUTUT: Hello

Welcome

Accessing Implementations Through Interface References

 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:

Example:
interface Callback {
void callback(int param);
}
class Client implements Callback {

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

// 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

The 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 contains variables and methods like a class but the methods in an interface are abstract
by default unlike a class. An interface extends another interface like a class implements an interface
in interface inheritance.

A program that demonstrates extending interfaces in Java is given as follows:


interface A {
void funcA();
}

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

interface B extends A {
void funcB();
}
class C implements B {
public void funcA() {
System.out.println("This is funcA");
}
public void funcB() {
System.out.println("This is funcB");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
}
}
OUTUT: This is funcA
This is funcB
Explanation:
Now let us understand the above program.
The interface A has an abstract method funcA(). The interface B extends the interface A and has an
abstract method funcB(). The class C implements the interface B. A code snippet which demonstrates
this is as follows:

interface A {
void funcA();
}
interface B extends A {
void funcB();
}
class C implements B {
public void funcA() {
System.out.println("This is funcA");

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

}
public void funcB() {
System.out.println("This is funcB");
}
}
In the method main() in class Demo, an object obj of class C is created. Then the methods funcA()
and funcB() are called. A code snippet which demonstrates this is as follows:

public class Demo {


public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
}
}

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.

 Here, we will have the detailed learning of creating and using user-defined packages.

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.

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

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.

EX: // Name of the package must be same as the directory


// under which this file is saved
package myPackage;

public class MyClass


{
public void getNames(String s)
{
System.out.println(s);
}
}
Now we can use the MyClass class in our program.

/* import 'MyClass' class from 'names' myPackage */


import myPackage.MyClass;

public class PrintName


{

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

public static void main(String args[])


{
// Initializing the String variable
// with a value
String name = "hello CIT";

// Creating an instance of class MyClass in


// the package.
MyClass obj = new MyClass();

obj.getNames(name);
}
}

Simple example of java package

The package keyword is used to create a package in java.

//save as Simple.java

package mypack;

public class Simple{

public static void main(String args[]){

System.out.println("Welcome to package");

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

For example
javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any directory

name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package

within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .

represents the current folder.

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.

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

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 of package that import the packagename.*

//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();

Output: Hello

2) Using packagename.classname

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname

//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();

Output:Hello

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.

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

Example of package by import fully qualified name

//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();

Output:Hello

 Sequence of the program must be package then import then class.

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

How to import packages in Java?

Java has an import statement that allows you to import an entire package (as in earlier examples),

or use only certain classes and interfaces defined in the package.

The general form of import statement is:

// To import a certain class only


import package.name.ClassName;
// To import the whole package
import package.name.*

For example,

import java.util.Date; // imports only Date class

import java.io.*; // imports everything inside java.io package

The import statement is optional in Java.

If you want to use class/interface from a certain package, you can also use its fully qualified name,

which includes its full package hierarchy.

Here is an example to import a package using the import statement.

import java.util.Date;

class MyClass implements Date {

// body

The same task can be done using the fully qualified name as follows:

class MyClass implements java.util.Date {

//body

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

Understanding CLASSPATH:

CLASSPATH: A classpath environment variable is the location from which classes are loaded at
runtime by JVM in java.

Classes may may include system classes and user-defined classes.

LOCATION: Locations is directory which may consist of class files or jar files(jar consists of class
files).

What if class is not available in classpath in java?

ClassNotFoundException is thrown when JVM tries to class from classpath but it does not find that
class.

How to configure classpath in CMD(command prompt) ?

First we will set the JDK path in windows >

What is Path? A path is a unique location of a file/ folder in a OS. PATH variable is also called system
variable or environment variable.

Go to My Computer, right click on properties

Click Advanced System setting, Environment Variable, New..

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

Then we will set environment variables

JAVA_HOME &

PATH >

1. set JAVA_HOME >

Variable name : JAVA_HOME

variable value: C:\Program Files\Java\jdk1.7.0_51 (Directory in which java has been installed)

Click OK.

2. set PATH >

Again click on New..

Then enter -

Variable name : PATH

variable value: C:\Program Files\Java\jdk1.7.0_51\bin

Click OK.

Prof.Bhairavi U N-Dept of MCA, CIT Mandya


OOPs with Java Programming 22MCA22

Setting temporary JAVA_HOME & PATH >

open cmd

type

set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_51

set PATH=C:\Program Files\Java\jdk1.7.0_51\bin

NOTE: Once you will exit cmd JAVA_HOME and PATH will be lost.

Prof.Bhairavi U N-Dept of MCA, CIT Mandya

You might also like