JAVA PROGRAMMING UNIT - II 2022-23
INTERFACES
Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body.
Once it is defined, any number of classes can implement an interface. Also, one class
can implement any number of interfaces.
To implement an interface, a class must create the complete set of methods defined by
the interface.
By providing the interface keyword, Java allows you to fully utilize the ―one
interface, multiple methods‖ aspect of polymorphism.
Interfaces are designed to support dynamic method resolution at run time. Normally,
in order for a method to be called from one class to another, both classes need to be
present at compile time so the Java compiler can check to ensure that the method
signatures are compatible.
Since interfaces are in a different hierarchy from classes, it is possible for classes that
are unrelated in terms of the class hierarchy to implement the same interface. This is
where the real power of interfaces is realized.
A programmer uses an abstract class when there are some common features shared by all the
objects. A programmer writes an interface when all the features have different
implementations for different objects. Interfaces are written when the programmer wants to
leave the implementation to third party vendors. An interface is a specification of method
prototypes. All the methods in an interface are abstract methods.
· An interface is a specification of method prototypes.
· An interface contains zero or more abstract methods.
· All the methods of interface are public, abstract by default.
· An interface may contain variables which are by default public static final.
· Once an interface is written any third party vendor can implement it.
· All the methods of the interface should be implemented in its implementation classes.
· If any one of the method is not implemented, then that implementation class should be
declared as abstract.
· We cannot create an object to an interface.
· We can create a reference variable to an interface.
· An interface cannot implement another interface.
· An interface can extend another interface.
· A class can implement multiple interfaces.
Defining an Interface
An interface is defined much like a class. This is the general form of an interface:
JAVA PROGRAMMING UNIT - II 2022-23
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value; }
Here, access is either public or not used. When no access specifier is included, then
default access results, and the interface is only available to other members of the
package in which it is declared.
When it is declared as public, the interface can be used by any other code. name is the
name of the interface, and can be any valid identifier. Notice that the methods which
are declared have no bodies. They end with a semicolon after the parameter list. They
are, essentially, abstract methods; there can be no default implementation of any
method specified within an interface.
Each class that includes an interface must implement all of the methods.
Variables can be declared inside of interface declarations. They are implicitly final
and static, meaning they cannot be changed by the implementing class. They must
also be initialized with a constant value.
All methods and variables are implicitly public if the interface, itself, is declared as
public.
interface Callback {
void callback(int param);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create
the methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
access class classname [extends superclass]
[implements interface [,interface...]] {
// class-body
}
Here, access is either public or not used. If a class implements more than one interface, the
interfaces are separated with a comma. If a class implements two interfaces that declare the
same method, then the same method will be used by clients of either interface. The methods
that implement an interface must be declared public. Also, the type signature of the
implementing method must match exactly the type signature specified in the interface
definition.
class Client implements Callback {
public void callback(int p) {
[Link]("callback called with " + p);
}
}
Page 18
JAVA PROGRAMMING UNIT - II 2022-23
Notice that callback( ) is declared using the public access specifier. When you implement an
interface method, it must be declared as public. It is both permissible and common for classes
that implement interfaces to define additional members of their own.
class Client implements Callback {
public void callback(int p) {
[Link]("callback called with " + p);
}
void nonIfaceMeth() {
[Link]("Classes that implement interfaces " +
"may also define other members, too.");
}
}
Accessing Implementations Through Interface References
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
[Link](42);
}
}
INTERFACES CAN BE EXTENDED
One interface can inherit another by use of the keyword extends. The syntax is the same as
for inheriting classes. When a class implements an interface that inherits another interface, it
must provide implementations for all methods defined within the interface inheritance chain.
Following is an example:
// One interface can extend another.
interface A {
void meth1();
void meth2();
}
interface B extends A {
void meth3();
}
class MyClass implements B {
public void meth1() {
[Link]("Implement meth1().");
}
public void meth2() {
[Link]("Implement meth2().");
}
public void meth3() {
[Link]("Implement meth3().");
}
Page 19
JAVA PROGRAMMING UNIT - II 2022-23
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
VARIABLES IN INTERFACE
The variables that are declared within an interface are implicitly static and final.
public interface A
{
int x=10;
}
class B implements A
{
int i;
B()
{
i=x+1;
}
void show()
{
[Link](i);
}
}
class Demo
{
public static void main(String args[])
{
B b=new B();
[Link]();
[Link](B.x);
}
}
MULTIPLE INHERITANCE USING INTERFACES
Java does not support multiple inheritance. But multiple inheritance can be achieved by using
interfaces.
interface Father
{ double PROPERTY = 10000;
double HEIGHT = 5.6;}
Page 20
JAVA PROGRAMMING UNIT - II 2022-23
interface Mother
{ double PROPERTY = 30000;
double HEIGHT = 5.4;}
class MyClass implements Father, Mother
{
void show()
{
[Link]("Total property is :" +([Link]+[Link]));
[Link] ("Average height is :" + ([Link] + [Link])/2 );
}
}
class InterfaceDemo
{
public static void main(String args[])
{
MyClass ob1 = new MyClass();
[Link]();
}
}
Page 21
JAVA PROGRAMMING UNIT - II 2022-23
INNER CLASSES
1) Nested static class doesn't need reference of Outer class but non static nested class or Inner
class requires Outer class reference. You can not create instance of Inner class without
creating instance of Outer class. This is by far most important thing to consider while making
a nested class static or non static. A static java inner class cannot have instances. A non-static
java inner class can have instances that belong to the outer class.
2) static class is actually static member of class and can be used in static context e.g. static
method or static block of Outer class.
3) Another difference between static and non static nested class is that you can not access non
static members e.g. method and field into nested static class directly. If you do you will get
error like "non static member can not be used in static context". While Inner class can access
both static and non static member of Outer class.
Uses of Inner Classes
It is a way of logically grouping classes that are only used in one place: If a class is useful
to only one other class, then it is logical to embed it in that class and keep the two together.
Nesting such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider two top-level classes, A and B, where B needs access to
members of A that would otherwise be declared private. By hiding class B within class A, A's
members can be declared private and B can access them. In addition, B itself can be hidden
from the outside world.
It can lead to more readable and maintainable code: Nesting small classes within top-level
classes places the code closer to where it is used.
Ex: non static inner class
class Outer
{
int x=10;
class Inner
{
void show()
{
[Link]("Hello "+x);
}
}
}
class Demo
{
public static void main(String args[])
{
Outer o=new Outer();
Page 22
JAVA PROGRAMMING UNIT - II 2022-23
[Link] i= [Link] Inner();
[Link]();
}
}
Ex: static inner class
class Outer
{
static int x=10;
static class Inner
{
void show()
{
[Link]("Hello "+x);
}
}
}
class Demo1
{
public static void main(String args[])
{
[Link] i= new [Link]();
[Link]();
}
}
Anonymous Inner Class
Anonymous inner classes of Java are called anonymous because they have no name.
Anonymous inner classes are anonymous and inline. They are essentially inner classes and
defined within some other classes.
Ex1:
public class Demo
{
public static void main(String[] args)
{
Dog dog = new Dog() {
public void someDog ()
{
[Link]("Anonymous Dog");
}
}; // anonymous class body closes here
Page 23
JAVA PROGRAMMING UNIT - II 2022-23
//dog contains an object of anonymous subclass of Dog.
[Link]();
}
}
class Dog
{
public void someDog()
{
[Link]("Classic Dog");
}
}
Ex2:
public class MainClass {
public static void main(String[] args) {
Ball b = new Ball() {
public void hit() {
[Link]("You hit it!");
}
};
[Link]();
}
interface Ball {
void hit();
}
}
Page 24
JAVA PROGRAMMING UNIT - II 2022-23
PACKAGES
A unique name had to be used for each class to avoid name collisions. The name you
choose for a class will be reasonably unique and not collide with class names chosen
by other programmers.
Java provides a mechanism for partitioning the class name space into more
manageable chunks. This mechanism is the package.
The package is both a naming and a visibility control mechanism. W can define
classes inside a package that are not accessible by code outside that package. We can
also define class members that are only exposed to other members of the same
package.
A package is the set of classes and interface that provides name space management
and access protection.
Defining a Package
To create a package is quite easy: simply include a package command as the first statement in
a Java source file. Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default package, which
has no name.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package.
For example, package MyPackage;
Java uses file system directories to store packages. More than one file can include the same
package statement. The package statement simply specifies to which package the classes
defined in a file belong. It does not exclude other classes in other files from being part of that
same package. Most real-world packages are spread across many files. You can create a
hierarchy of packages. To do so, simply separate each package name from the one above it by
use of a period.
The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system.
For example, package [Link];
Page 25
JAVA PROGRAMMING UNIT - II 2022-23
Understanding CLASSPATH
Packages are mirrored by directories. This raises an important question: How does the
Java run-time system know where to look for packages that you create? The answer
has two parts.
First, by default, the Java run-time system uses the current working directory as its
starting point. Thus, if your package is in the current directory, or a subdirectory of the
current directory, it will be found.
Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
Setting up Java Environment:
After installing the JDK, we need to set at least one environment variable in order to able to
compile and run Java programs. A PATH environment variable enables the operating system
to find the JDK executables when our working directory is not the JDK's binary directory.
· Setting environment variables from a command prompt: If we set the variables from a
command prompt, they will only hold for that session. To set the PATH from a command
prompt:
set PATH=C:\Program Files\Java\jdk1.5.0_05\bin;
Setting environment variables as system variables:
If we set the variables as system variables they will hold continuously.
o Right-click on My Computer
o Choose Properties
o Select the Advanced tab
o Click the Environment Variables button at the bottom
o In system variables tab, select path (system variable) and click on edit button
o A window with variable name path and its value will be displayed.
o Don’t disturb the default path value that is appearing and just append (add) to that path at
the end:
;C:\ProgramFiles\Java\ jdk1.5.0_05\bin;
o Finally press OK button.
Page 26
JAVA PROGRAMMING UNIT - II 2022-23
package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
[Link]("--> ");
[Link](name + ": $" + bal);
}
}
class AccountBalance {
Page 27
JAVA PROGRAMMING UNIT - II 2022-23
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
Call this file [Link], and put it in a directory called MyPack. Next, compile
the file. Make sure that the resulting .class file is also in the MyPack directory. Then try
executing the AccountBalance class, using the following command line:
java [Link]
Remember, you will need to be in the directory above MyPack when you execute this
command, or to have your CLASSPATH environmental variable set appropriately. As
explained, AccountBalance is now part of the package MyPack. This means that it cannot be
executed by itself. That is, you cannot use this command line:
java AccountBalance
Access Protection
Java addresses four categories of visibility for class members:
■ Subclasses in the same package
■ Non-subclasses in the same package
■ Subclasses in different packages
■ Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories.
Anything declared public can be accessed from anywhere.
Anything declared private cannot be seen outside of its class.
When a member does not have an explicit access specification, it is visible to subclasses as
well as to other classes in the same package. This is the default access.
If you want to allow an element to be seen outside your current package, but only to classes
that subclass your class directly, then declare that element protected.
A class has only two possible access levels: default and public. When a class is declared as
public, it is accessible by any other code. If a class has default access, then it can only be
accessed by other code within its same package.
Page 28
JAVA PROGRAMMING UNIT - II 2022-23
Private No modifier Protected Public
Same class Yes Yes Yes Yes
Same package
subclass No Yes Yes Yes
Same package
non-subclass No Yes Yes Yes
Different
package
subclass No No Yes Yes
Different
package
non-subclass No No No Yes
Importing Packages
Given that packages exist and are a good mechanism for compartmentalizing diverse
classes from each other, it is easy to see why all of the built-in Java classes are stored
in packages. There are no core Java classes in the unnamed default package; all of the
standard classes are stored in some named package. Since classes within packages
must be fully qualified with their package name or names, it could become tedious to
type in the long dot-separated package path name for every class you want to use. For
this reason, Java includes the import statement to bring certain classes, or entire
packages, into visibility. Once imported, a class can be referred to directly, using only
its name.
The import statement is a convenience to the programmer and is not technically
needed to write a complete Java program. If you are going to refer to a few dozen
classes in your application, however, the import statement will save a lot of typing.
In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions.
This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package
inside the outer package separated by a dot (.).Finally, you specify either an explicit
classname or a star (*), which indicates that the Java compiler should import the entire
package.
The star form may increase compilation time—especially if you import several large
packages. For this reason it is a good idea to explicitly name the classes that you want to use
Page 29
JAVA PROGRAMMING UNIT - II 2022-23
rather than importing whole packages. However, the star form has absolutely no effect on the
run-time performance or size of your classes.
All of the standard Java classes included with Java are stored in a package called java. The
basic language functions are stored in a package inside of the java package called [Link].
Normally, you have to import every package or class that you want to use, but since Java is
useless without much of the functionality in [Link], it is implicitly imported by the
compiler for all programs.
import [Link].*;
class MyDate extends Date {
}
The same example without the import statement looks like this:
class MyDate extends [Link] {
}
Example:
package MyPack;
public class Factorial
{
public int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}
}
import MyPack.*;
class Test {
public static void main(String args[]) {
Factorial f=new Factorial();
[Link]([Link](5));
}
}
Page 30