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

Java 3rd UNIT(Chapter-2)

Java 3rd UNIT(Chapter-2)
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java 3rd UNIT(Chapter-2)

Java 3rd UNIT(Chapter-2)
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

JAVA PROGRAMMING

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.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

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

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

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

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

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:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

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
{

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

public static void main(String arg[])


{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Output:

Interface vs. abstract class

abstract Classes Interfaces

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

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

concrete methods methods

A class can implement any number of


4 A class can extend only one abstract class
interfaces

In an interface keyword ‘abstract’ is


In abstract class keyword ‘abstract’ is
5 optional to declare a method as an
mandatory to declare a method as an abstract
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;

🡪Java uses file system directories to store packages.


🡪For example, the .class files for any classes you declare to be part of MyPackage must be stored
in a directory called MyPackage.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

🡪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;


In order for a program to find MyPack, one of three things must be true.
Either the program can be executed from a directory immediately above MyPack, or the
CLASSPATH must be set to include the path to MyPack, or the -classpath option must specify
the path to MyPack when the program is run via java.
● When the second two options are used, the class path must not include MyPack, itself.It
must simply specify the path to MyPack.
For example, in a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack Then the class path to MyPack is C:\MyPrograms\Java

Example:
package MyPack;
class pack
{
public static void main(String args[])

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

{
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

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

🡪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.

Private Default 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

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

//same package sub class


package p1;
public class samepackage_subclass extends samepackage_sameclass
{
public samepackage_subclass()
{
System.out.println("same package sub class");
System.out.println("-------------------------------------");
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_non_subclass .java in p1


//same package non-sub class
package p1;
public class samepackage_non_subclass
{
public samepackage_non_subclass()
{
samepackage_sameclass obj=new samepackage_sameclass();
System.out.println("same package non-sub class");
System.out.println("-------------------------------------");
System.out.println("Default Value="+obj.default_x);
System.out.println("Protected Value="+obj.protected_x);
System.out.println("Public Value="+obj.public_x);
System.out.println("====================================");

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

}
}

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);
}
}

Save as main_access.java in original directory


import p1.*;
import p2.*;
public class main_access
{
public static void main(String arg[])
{
samepackage_sameclass o1=new samepackage_sameclass();
o1.display();
samepackage_subclass o2=new samepackage_subclass();
samepackage_non_subclass o3=new samepackage_non_subclass();
otherpackage_subclass o4=new otherpackage_subclass();
otherpackage_non_subclass o5=new otherpackage_non_subclass();
}

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

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.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

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

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

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.

Methods of Object class


The Object class provides many methods. They are as follows:

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.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

protected Object clone() throws creates and returns the exact copy (clone) of
CloneNotSupportedException this object.

public String toString() returns the string representation of 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).

protected void finalize()throws is invoked by the garbage collector before


Throwable object is being garbage collected.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

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.

How to Define and Use an Enumeration

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

Java, Cpp, C, Dbms

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{

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


JAVA PROGRAMMING

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

class Demo

public static void main(String args[])

WeekDays wk; //wk is an enumeration variable of type WeekDays

wk = WeekDays.SUNDAY;

System.out.println("Today is "+wk);

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE

You might also like