Java 3rd UNIT(Chapter-2)
Java 3rd UNIT(Chapter-2)
UNIT-3(Chapter-2)
Interfaces, Packages and Enumeration
Interfaces
Defining an Interface
An interface is defined much like as an abstract class (it contains only method declarations).It
contains constants and method declarations.
Syntax:
accessspecifier interface interfacename
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
datatype varname1 = value;
datatype varname2 = value;
// ...
return-type method-nameN(parameter-list);
datatype varnameN = value;
}
🡪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. In this case, the interface must be the only public
interface.
Note: that the methods 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. All
methods and variables are implicitly public.
Example:
public interface animal
{
void display();
}
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.
Syntax:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
🡪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.
public interface Animal
{
}
public class Interface implements Animal
{
}
Applying Interfaces
interface Animal
{
void moves();
}
interface Bird
{
void fly();
}
abstract class flowers
{
abstract void beauty();
}
public class interfacedemo extends flowers implements
Animal,Bird
{
public void moves()
{
System.out.println("animals move on land");
}
public void fly()
{
System.out.println("birds fly in air");
}
public void beauty()
{
System.out.println("flowers are beautiful");
}
public static void main(String args[])
{
interfacedemo id=new interfacedemo();
id.moves();
id.fly();
id.beauty();
}
}
Output:
Variables in Interfaces
🡪You can use interfaces to import shared constants into multiple classes by simply declaring an
interface that contains variables that are initialized to the desired values. 🡪When you include that
interface in a class (that is, when you “implement” the interface), all of those variable names will
be in scope as constants. (This is similar to using a header file in C/C++ to create a large number
of #defined constants or const declarations.)
🡪If an interface contains no methods, then any class that includes such an interface doesn’t
actually implement anything.
🡪It is as if that class were importing the constant fields into the class name space as final
variables.
Example:
interface arithmetic
{
Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE
JAVA PROGRAMMING
int a=10;
int b=2;
int c=15;
int d=6;
}
class operations implements arithmetic
{
public static void main(String args[])
{
int e,f,g,h;
e=a+b;
f=c-d;
g=e*f;
h=e/f;
System.out.println("addition of"+a+ "and"+b+ "is:"+e);
System.out.println("subtraction of"+c+ "and"+d+ "is:"+f);
System.out.println("multiplication of"+e+ "and"+f+ "is:"+g);
System.out.println("division of"+e+ "and"+f+ "is:"+h);
}
}
Output:
Extending Interfaces
🡪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.
Example:
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
class MyClass implements B
{
public void meth1()
{
System.out.println("Method1 Implementation");
}
public void meth2()
{
System.out.println("Method2 Implementation");
}
public void meth3()
{
System.out.println("Method3 Implementation");
}
}
class IFExtend
{
abstract class can extend only one class or one interface can extend any number of
1
abstract class at a time interfaces at a time
abstract class can extend from a class or from interface can extend only from an
2
an abstract class interface
3 abstract class can have both abstract and interface can have only abstract
abstract class can have protected , public and Interface can have only public abstract
6
public abstract methods methods i.e. by default
abstract class can have static, final or static interface can have only static final
7
final variable with any access specifiers (constant) variable i.e. by default
Packages
Defining a Package: Packages are containers for classes that are used to keep the class name
spaceCompartmentalized. Packages are stored in a hierarchical manner and are explicitly imported
into new class definitions.
Creating 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.
Syntax: package packagename;
Example: package MyPackage;
🡪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.
🡪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:
package pkg1[.pkg2[.pkg3]];
CLASSPATH
How does the Java run-time system know where to look for packages that you create?
The answer has three parts.
First, by default, the Java run-time system uses the current working directory as its starting point.
Thus, if your package is in 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.
Third, you can use the -classpath option with java and javac to specify the path to your classes.
Example:
package MyPack;
class pack
{
public static void main(String args[])
{
int a=10;
int b=2;
System.out.println("Welcome to Packages Concept");
System.out.println("Addition of"+a+"and"+b+"is"+(a+b));
}
}
Output:
🡪Call this file pack.java and put it in a directory called MyPack. Next, compile the file. Then,
executing the pack class, using the following command line:
java MyPack. Pack
Accessing a Package
🡪Java provides many levels of protection to allow fine-grained control over the visibility of
variables and methods within classes, subclasses, and packages.
🡪Classes and packages are both means of encapsulating and containing the name space and scope
of variables and methods.
🡪Packages act as containers for classes and other subordinate packages. Classes act as containers
for data and code.
🡪The class is Java’s smallest unit of abstraction. Because of the interplay between classes and
packages, 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.
Example:
Save as samepackage_sameclass.java in p1
//same package same class
package p1;
public class samepackage_sameclass
{
private int private_x=10;
Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE
JAVA PROGRAMMING
int default_x=20;
protected int protected_x=30;
public int public_x=40;
public void display()
{
System.out.println ("same package same class");
System.out.println("-------------------------------------");
System.out.println ("Private Value="+private_x);
System.out.println("Default Value="+default_x);
System.out.println("Protected Value="+protected_x);
System.out.println ("Public Value="+public_x);
System.out.println ("========================================");
}
}
Save as samepackage_subclass.java in p1
}
}
Save as otherpackage_subclass.java in p2
//other package sub class
package p2;
public class otherpackage_subclass extends p1.samepackage_sameclass
{
public otherpackage_subclass()
{
System.out.println("other package sub class");
System.out.println("-------------------------------------");
System.out.println("Protected Value="+protected_x);
System.out.println("Public Value="+public_x);
System.out.println("========================================");
}
}
Save as otherpackage_non_subclass.java
//other package non-sub class
package p2;
public class otherpackage_non_subclass
{
public otherpackage_non_subclass()
{
p1.samepackage_sameclass obj1=new p1.samepackage_sameclass();
System.out.println("other package non-sub class");
System.out.println("-------------------------------------");
System.out.println("Public Value="+obj1.public_x);
}
}
Output:
Importing Packages
🡪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|*);
Example:
import java.util.Date;
import java.io.*;
import java.util.*;
java.lang package:
Provides classes that are fundamental to the design of the Java programming language. The most
important classes are Object, which is the root of the class hierarchy, and Class, instances of
which represent classes at run time.
The classes String and StringBuffer similarly provide commonly used operations on character
strings.
Object class
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
Method Description
public final Class getClass() returns the Class class object of this object.
The Class class can further be used to get the
metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of
CloneNotSupportedException this object.
public final void notify() wakes up single thread, waiting on this object's
monitor.
public final void notifyAll() wakes up all the threads, waiting on this
object's monitor.
public final void wait(long causes the current thread to wait for the
timeout)throws InterruptedException specified milliseconds, until another thread
notifies (invokes notify() or notifyAll()
method).
public final void wait(long timeout,int causes the current thread to wait for the
nanos)throws InterruptedException specified milliseconds and nanoseconds, until
another thread notifies (invokes notify() or
notifyAll() method).
public final void wait()throws causes the current thread to wait, until another
InterruptedException thread notifies (invokes notify() or notifyAll()
method).
Enumeration
Enumerations was added to Java language in JDK5. Enumeration means a list of named
constant. In Java, enumeration defines a class type. An Enumeration can have constructors,
methods and instance variables. It is created using enum keyword. Each enumeration constant
is public, static and final by default. Even though enumeration defines a class type and have
constructors, you do not instantiate an enum using new. Enumeration variables are used and
declared in much a same way as you do a primitive variable.
1. An enumeration can be defined simply by creating a list of enum variable. Let us take an
example for list of Subject variable, with different subjects in the list.
//Enumeration defined
enum Subject
2. Identifiers Java, Cpp, C and Dbms are called enumeration constants. These are public,
static and final by default.
3. Variables of Enumeration can be defined directly without any new keyword.
Example:
enum WeekDays{
class Demo
wk = WeekDays.SUNDAY;
System.out.println("Today is "+wk);