[go: up one dir, main page]

0% found this document useful (0 votes)
31 views27 pages

Java Unit-2

The document explains the concept of interfaces in Java, which provide a way to achieve multiple inheritance, allowing classes to implement multiple interfaces. It covers the definition, extension, and implementation of interfaces, as well as the differences between interfaces and abstract classes. Additionally, it discusses Java packages, their benefits, how to create and access them, and the use of static imports.
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)
31 views27 pages

Java Unit-2

The document explains the concept of interfaces in Java, which provide a way to achieve multiple inheritance, allowing classes to implement multiple interfaces. It covers the definition, extension, and implementation of interfaces, as well as the differences between interfaces and abstract classes. Additionally, it discusses Java packages, their benefits, how to create and access them, and the use of static imports.
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/ 27

Unit-II

INTERFACE:-
➢ Java does not support multiple inheritance i.e., classes in java cannot have more than one super
classes.
➢ For instance, a definition like class A extends B
extends C
{

}
is not permitted in java
➢ Java provides an alternative approach known as interfaces. To support the concept of multiple
inheritances.
➢ An interface is basically a kind of class it can implement more than one interfaces, thereby
enabling us to create classes that built upon other classes without the problems created by
multiple inheritance.
Defining interfaces:-
➢ An interface is basically a kind of class Like classes, interfaces contain methods and variables
but with a major difference.
➢ The difference is that interfaces define only abstract methods and final fields.
➢ This means that interfaces do not specify any code to implement these methods and data
fields contain only constants.
➢ The syntax for defining an interface is very similar to that for defining a class.
➢ The general form of an interface definition is interface
interfacename
{
Variable declaration;
Method declaration;
}
➢ Here interface is a keyword and interface name is any valid java variable.
➢ Variables are declared as follows.
Static final type variable = Value;
Note that all variables are declared as constants.
Methods declaration will contain only a list of methods, without anybody statements.
Example:-
return type method name (parameter lists);

❖ There is an example of an interface definition that contains two variables and one
method
interface item
{
Static final int code = 1001; Static final
string name = “FAN”; void displays( );
}
Extending interfaces:-
❖ Like classes, interfaces can also be extended i.e., an interface can be sub interfaced
from other interfaces.
❖ The new sub interface will inherit all the members of the super interface in the manner
similar to sub class.
❖ This is achieved using the keyword extends as shown below
interface name2 extends name1
{
Body of name 2;
}
❖ For Example we can put all the constants in one interface and the methods in the other.
❖ This will enable us to use the constants in classes where the methods are not require .
Example:-
interface Itemconstants
{
int code = 1001; String
name = “FAN”
}
interface Item extends Itemconstants
{
void display ( );
}
❖ The interface item would inherit both the constants code and name into it.
❖ We can also combine several interfaces together into a single interface Following
declarations are valid.
interface Itemconstants
{
int code = 1001; String
name = “FAN”
}
interface ItemMethods
{
void display ( );
}
interface Item extends Itemconstants, Item methods
{

}
❖ While interfaces are allowed to extend the other interfaces, sub interfaces cannot define
the methods declared in the super interfaces.
❖ After all sub-interfaces are still interfaces not classes. Instead it is the responsible of any
class that implements the derived interface to define all the methods.
Implementing interfaces:-
❖ Interfaces are used as super classes whose properties are inherited by classes
❖ It is therefore, necessary to create a class that inherits the given interface.
❖ This is done as follows.
class classname implements interface
{
body of class name;
}
❖ Here the class classname “implements” the interface interfacename.
❖ A more general form of implementation may look like this.
class classname extends superclass implements Interface 1, Interface2,----
{
body of class name ;

}
❖ This shows that a class can extend another class while implementing interfaces
❖ When a class implements more than one interfaces, they are separated by a comma
❖ The implementation of interfaces can take various forms as illustrated in the below
figure.
Interface Extension.

Interface A Class Extension A D


implementation

Class Extension B Class Extension B E

Class Class interface implementation.


C C

(a) (b)

Interface A interface A interface B


Extension

Implementation
B C C Interface
Class Class implementation

Fig(a):various forms of interface implementation


D claaa

//demonstrate for implements an interface


interface Area
{
float pi=3.14f;
float compute (float x, float y);
}
class Rectangle implements Area
{
public float compute (float x, float y)
{
return(x*y);
}
}
class circle implements Area{
public float compute (float x, float y)
{
return(pi *x*x);
}
}
class interfacetest{
public static void main (String k[ ]){
Rectangle rect =new Rectangle( ); Circle
cir= new Circle ( );
Area ar; //interface object
ar=rect; //interface object
System.out.println(“rectangle =”+ar.compute (10,9)); ar =cir;
//interface object
System.out.println (“circle Area=”+ar.compute(10,0));
}}
Accessing interface variables:-
❖ Interfaces can be used to declare a set of constants that can be used in different
classes.
❖ This is similar to creating header files in c++ to contain a large number of constants.
❖ Since such interfaces do not contain methods there is no need to worry about
implementing any methods.
❖ The constant values will be available to any class that implements the interface.
Example:- interface A
{
int m=10;
int n= 50;
}
class B implements A
{
int x=m; //Accessing interface constant void
methodB (int size)
{
if (size<n)

}
}
Multiple Inheritances implementing by using interface:-
A sub class has the several super classes is called as the multiple inheritance.Java does not directly
implement multiple inheritances. However this concept is implementing using a secondary
inheritance path in the form of interface.

A B Base/Super/Parent

Derived/Sub/Child
C
//demonstrative for implements multiple inheritances by using interface.
class student
{
int Rollnumber;
void getrollnumber(int a)
{
Rollnumber=a;
}
void putnumber( )
{
System.out.println(“Rollnumber=”+Rollnumber);
}
}
class Test extends Student
{
float part1, part2;
void getmarks (int M, int N)
{
Part1=M;
Part2=N;
}
void putmarks( )
{
System.out.println (“marks obtained”);
System.out.println(“marks1=”+part1);
System.out.println(“marks2=”+part2);
}
}
interface sports
{
float sportwt=6.0f;
void putsportwt( );
}
class results extends Test implements sports
{
float total;
public void putsportwt( )
{
System.out.println(“sportwt=”+sportwt);
}
void display( )
{
total=part1+part2+sportwt;
putnumber( );
putmarks( );
putsportwt( );
System.out.println (“total marks=”+total);
}
}
class multipleinherittest{
public static void main (String k[ ]{ results
res=new results( ); res.getrollnumber(163);
res.getmarks(98f, 95f);
res.display ( );
}
}
Interface Vs Abstract Classes in Java
There are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract
non-abstract methods. methods.

2) Abstract class doesn't support multiple Interface supports multiple


inheritance. inheritance.

3) Abstract class can have final, non- final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java An interface can extend another Java
class and implement multiple Java interfaces. interface only.

7) An abstract class can be extended using An interface can be implemented using


keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are
members like private, protected, etc. public by default.

9)Example: Example:
public abstract class Shape{ public public interface Drawable{ void
abstract void draw(); draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Example of abstract class and interface in Java
Let's see a simple example where we are using interface and abstract class both.
//Creating interface that has 4 methods
interface A
{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}
//Creating abstract class that provides the implementation of one method of A interfa
ce
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 re
st 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();
}
}

PACKAGE:-
Packages are java‟s way of grouping a variety of classes and interfaces together. The grouping is
usually done according to functionality. In fact, packages act as “container” for classes.
Packages provide the following benefits.
• The classes contain in the package and the programs can easily reduce.
• Two classes in two different packages can have the same name.
• Packages provide a way to hide.
• The classes or packages can also provide a way to separating design from code. Java
packages are therefore classified into two types. The first category is known as Java API
packages and the second is known as user defined packages.
Java API packages (or) Predefined packages:-
Java API provides a large number of classes grouped into different packages according to
functionality. Most of the time we use the packages available with the Java API as shown in the
below figure.

Java

lang util io awt net applet

Fig (a) Frequently used API Packages. Java


System Packages and Their Classes

Package Name Contents

java.lang Language support classes. They include classes for


primitive types, strings, math functions, threads and
exceptions.

java.util Language utility classes such as vectors, hash tables, random


numbers, date, etc.

java.io input/output support classes. They provide facilities for the input
and output of data.

java.awt Set of classes for implementing graphical user interface. They


include classes for windows, buttons, lists, menus and so on.

java.net classes for networking. They include classes for


communicating with local computers as well as with internet
servers.

java.applet classes for creating and implementing applets.


Using System Packages:-
The packages are organized in a hierarchical structure as shown in the below Figure. That the package
named java contains the package awt, which in Turn contains various classes required for
implementing graphical user Interface.

Java
awt Color Package containing awt Package.
Package Containing
Graphics Classes.
Font

Image Classes containing


Methods

Fig(a) Hierarchical Representation of java.awt package.


There are two ways of accessing the classes stored in a package. The first approach is to use the fully
qualified class name of the class that we want use. This is done by using the package name containing
the class and then appending the class name to it using the dot(.) operator. For example , if we want to
refer to the class Color in the awt package, then we may do so as follows:
java.awt.Colour;
Notice that awt is a package within the package java and the hierarchy is represented by separating the
levels with dots(.).
We may like to use many of the classes contained in a package. We may achieve this easily as follows:
import packagename.classname;
(or)
import packagename.*;
These are known as import statements and must appear at the top of the file, before any class
declarations, import is a keyword.
Naming Conventions:-
Packages can be named using the standard java naming rules. By convention, however, packages
begin with lowercase letters. We know that all class names begin with an uppercase letter. For
example, look at the following statement:
java.lang.Math.sqrt(x);

Package Class Method


Name Name Name
This statement uses a fully qualified class name Math to invoke the method sqrt().
Package:-
Packages are java‟s way of grouping a variety of classes and interfaces
together. The grouping is usually done according to functionality. In fact, packages act as
“container” for classes.
Creating Packages:-
To create the packages in java very easily, we must first declare the name of the package using
the package keyword followed by a package name.
package packagename;
Package name is any java valid identifier.
Example :
package pack1; //create package
package student; //create another package
This must be the first statement in a java source file. Then we define a class, just as we normally
define class.
package firstpackage; //package declaration public
class firstclass //class definition
{

//body of class

}
Creating our own package involves the following steps:
1. Declare the package at the beginning of a file using the form.

package packagename;
2. Defines the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source files are Stored.
4. store the listing as the classname.java file in the subdirectory created.
5. compile the file. This creates .class file in the subdirectory.
Accessing Package:-
It may be recalled that we have discussed earlier that a java system package can be accessed
either using a fully qualified class name or using a shortcut approach through the import
statement. The same approaches can be used to access the user-defined packages as well. The
import statement can be used to search a list of packages for a particular class. The general
form of import statement for searching class is as follows.

import package1.packag2.package3.classname;
We can also use another approach as follows.

import packagename.*;
Example:-
import firstpackage.*;
Using a Package:-
Let us now consider some simple programs that will use classes from other packages. The listing
below shows a package named package1 containing a single class A.
package package1;
public class A
{
public void displayA()
{
System.out.println(“package package1 containing class A”);
}
}
This source file should be named A.java and stored in the subdirectory package1. The resultant
A.class will be stored in the same subdirectory.
The package1 containing one class, class A. package1 can access the another program as
shown in the below program.
import package1.A;
class ptest
{
public static void main(String k[])
{
A a=new A();
a.displayA();
}
}
The source file ptest.java will be saved and then compiled. Now we can run the program and
obtain the result.
Hide a class in a Package:-
We can import a package using (*) for all public classes. We may not import some classes. That
is we can hide some classes from accessing and from outside of the package. Subclasses should
be declared not public.
Here class A is available and class B is hidden from the package. p1 becauseit cannot be declared
as public.

package p1;

public class A

{
- --------- //available out side
}
class B
{
..///hidden to outside
}
Static import:-
It is similar to general import statement in java. The static import statement imports static
methods and members from package. The general syntax is Import static
packagename.classname.members;
import static java.lang. Math;

public class ptest {


public void circle(double d){ double a= PI*d*d; System.out.println("area="+a);}
public static void main(String args[])
{
ptest p=new ptest(); p.circle(2.3);
}
Java.lang Package:he package java.lang contains classes and interfaces that are essential to
the Java language. These include:

Object, the ultimate superclass of all classes in Java

• Thread, the class that controls each thread in a multithreaded program


• Throwable, the superclass of all error and exception classes in Java
• Classes that encapsulate the primitive data types in Java
• Classes for accessing system resources and other low-level entities
• Math, a class that provides standard mathematical methods
• String, the class that is used to represent strings
Because the classes in the java.lang package are so essential, the java.lang package is implicitly
imported by every Java source file. In other words, you can refer to all of the classes and
interfaces in java.lang using their simple names.The following figure shows the class hierarchy
for the java.lang package.
Access Protection (Visibility Modifiers):-
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Exceptions and Assertions
Errors:-
• Mistake might lead to an error causing to program to produce unexpected results.
• Errors are the wrongs that can make a program go wrong
• An error may produce an in correct output or may terminate the execution of the program
abruptly or even may causes the system to crash.

Types of error:-
• Errors may broadly be classified into two categories.
1. Compile- time errors
2. Run-time errors
Compile- time error:-
• All syntax errors will be detected and displayed by the java complier and therefore
these errors are known as compile time errors.
• Whenever the complier displays an error it will not create the .class file.
• Example program for the compile time error.
• This program contains an error */
//demonstrate for compile time error import
java.io.*;
class Error1
{
public static void main (String args[ ])
{
System.out.println (“Hello java”) //missing semicolon(;)
}
}
→ From the above program we have missed the semicolon at the end of print statement then the
following message will be displayed in the screen.
Error 1.java: 5: „;‟ expected
System.out.println (“Hello java”)
^
1 error

Most of the compile time errors are due to typing mistakes. The most common problems are:
1. Missing semi colons
2. Missing brockets in classes and method
3. Miss spelling of identifiers and key word.
4. Missing double quotes in strings
5. Use of undeclared variables
6. In compatible types in assignments/ initialization
7. Bad reference to objects
8. Use of assignment (=) in place of assignment == operator

Run-Time Errors:-
• Sometimes a program may compile successfully creating the .class file but may not run
properly.
• Such programs may produce wrong results due to wrong logic or may terminate due to
errors such as stack over flow.
• Most common run time errors are:
→ Dividing an integer by Zero
→ Accessing an element i.e., out of the bounds of an array.
→ Trying to store a value into an array of an incompatibles type or class.
→ Trying to cast an instance of a class to one of its subclasses.
→ Passing a parameter that it is not in a valid range or value for a method.
→ Trying to illegally change the state of a thread.
→ Trying to illegally change the state of a thread.
→ Attempting to use a negative size for an array.
→ Converting invalid string to a number
→ Accessing a character that is out of bounds of a string
Example program for the run time errors.
//demonstrate for runtime errors import
java.io.*;
class Error2{
public static void main(String args[ ]){ int
a=10;
int b=5;
int c=5;
int x=a/(b-c); //Division by zero
System.out.println (“x=”+x); int
y=a/(b+c); System.out.println
(“Y=”+y);
} }
• These above program syntactically correct and therefore do not cause any problem
during compilation.
• However while executing, it displays the following message and stops out executing
further statements.
java.long.Airthmetic Exception / by zero at Error2.main(Error2.java.10).

Exception:-
An exception is a condition that is caused by a run time error in the program. When the java
interpreter encounters a error such as dividing an integer by zero, it creates an excep tion object
and throws it i.e., informs us that an error has occurred
→ If we want the program to continue with the error. Then we should try to catch the
exception object thrown by the error condition and then display an appropriate message
for taking corrective actions. This task is known as exception handling.
→ The purpose of exception handling mechanism is to provide a means to detect and report an
“exceptional circumstance”. So that appropriate action can be taken.

→ The mechanism suggests incorporation of a separate error handling code that performs the
following tasks.

Exception type Caused of Exception

1. Find the problem (Hit the exception)


2. Informs that an error has occurred (throw the exception)
3. Receive the error information (catch the exception)
4. Take corrective actions (Handle the exception)
• The error handling code basically consists of two segments, one to detect errors and to
throw exceptions and the other to catch the exceptions and take to appropriate actions.
• Some common exceptions that we must watch out for catching are listed in table.
AirthmeticExceptions Caused by math error such as
division by zero
ArrayIndexOutOfBoundsException Caused by b ad array indexes

ArrayStoreException Caused when a program tries to


store a wrong type of data in an array

FileNotFoundException Caused by an attempt to access a


non existing file
IOException Caused by an attempt to access a
non existing file
NullPointerExecption Caused by generator input/output
failures
NumberFormatException Caused when a converts b/w
strings and numbers
OutOf MemoryExecption Caused then there is not enough
memory allocate a new object
Security Exception Tries to perform an action not
allowed by the browser security space

StackOverFlowException Caused when the system runs out


of stacked space
String IndexOutOf Bounds Exception Caused when a program attempts to
access a non existing character
position in a string

Syntax of Exception Handling Code:

The basic concepts of exception handling are throwing an exception and catching it. Java uses
a keyword a try to preface a block of code that is likely to cause an error condition
and throw a exception
▪ A catch block defined by the keyword “catch” catches the exception
thrown by the try block that handles it approximately
▪ The following example illustrates the use of simple try and catch
statements
try
{
Statement; //generates an exception
}
catch(Exception e)
{
Statement; //process the Exception
}

▪ The try block can have one or more statements that could generate an exception
▪ If anyone statement generates an exception, the remaining statements in the block are
shipped and execution jumps to the catch block i. e, placed next to the try block
▪ Every try statement should be followed by at least one catch statement otherwise an
error may occurs
▪ Example program for the exception handling mechanism
//demonstrate for error handling mechanism
class error3
{
public static void main(Strings args[])
{
int a=10;
int b=5;
int c=5;
int x, y;
try
{
x=a/(b-c); // exception object is created
}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero”); // exception is handling
}
y=a/(b+c);
System.out.println (“y=”+y);
}}
Multiple catch statement:-
It is possible to have more than one catch statement in the catch block as illustrate
below:

try
{
Statement; // generates an exception
}
catch(Exception –type-1 e)
{
Statement; // progess exception type-1
}

catch(Exception- type-2 e)
{
Satement ; // process exception type-2
}
:
:
catch (Exception- type-n e)
{
Statement ; // process exception type-n
}

When an exception in a try block is generated, the java treats the multiple catch
statements like cases in a switch statement.
Example program for multiple catch statement
// demonstrate for multiple catch statement
import java.io.*;
class multiplecatch
{
public static void main (String args[])
{ int a[]={5,10}
int b =5;
int x, y;
try
{
x= a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println (“division by zero”);
}
catch(ArrayIndexoutof BoundsException e);
{
System. Out.println(“Array index out of Bound”);
}
catch(ArrayStoreException e)
{
System.out.println(“wrong data type ”);

}
y= a[1]/a[0];
System.out.println(“y=”+y);
}}
Throwing our own exception:-
» There may be times when we would like to throw our own exceptions
» We can do this by using the keyword throw as follows
throw new Throwable_ subclass;
Examples:
throw new ArithmeticException();
throw new NumberFormatException();
Example program for the throwing our own exception
// demonstrate for throwing our own exception
import java.lang.Exception;
class myException extends Exception
{
My Exception(String message)
{
Super (message);
}
}
class TestmyException{
public static void main(String args[]){
int x = 5, y = 100;
try
{
float z = (float) x / (float)y;
if (z<0.01)
{
throw new MyException (“Number is too small”);
}
}
catch (MyException e)
{
System.out .println(“caught my Exception”);
System.out.println(e.getMessage());
}
finally
{
System.out.println(“I am always here”);
}
} }
Using finally statement:-
✓ Java supports another statement know as finally statement that can be
used to handle an exception that is not caught by any of the previous
catch statements.
✓ Finally block can be used to handle any exception generated within a try
block.
✓ It may be added immediately after the try block or after the last catch
block shown as follows :
try try
{ {

} }
finally catch(…)
{ {

} }
catch(…..)
{
}
finally
{

}
Exception Encapsulation, Enrichment and Assertions:

Exception encapsulation and enrichment


The process of wrapping the caught exception in a different exception is called
"Exception Encapsulation". The Throwable super class has added one parameter in its
constructor for the wrapped exception and a "getCause()" method to return the
wrapped exception. Wrapping is also used to hide the details of implementation.
Syntax:
try
{

}
throw new ArithmeticException();
catch(AritmeticExceptions ae)
{
//wrapping exception
throw new ExcepDemo("Testing User Exception",ae);
}
Disadvantages of wrapping:
1. It leads to the long Stack traces.
2. It is a difficult task to figure out where the
exception is Solution:
The possible solution is Exception enrichment. Here we don‟t
wrap exception but we add some information to the already thrown
exception and rethrow it.
Example program:
class ExcepDempo extends Exception
{
String
message;
ExcepDem
o(String
msg)
{
message=msg;
}
public void addInformation(String msg)
{
message=message+msg;
}
}

class ExcepEnrich
{
static void testException()
{
try{

throw new ExcepDemo("Testing user Exception:");


catch(ExcepDemo e)
{
e.addInformation("Example Exception");
}
}
public static void main(String args[])
{
try
{
testException();
}
catch(Exception e)
{

System.out.println(e);
}
}
}
Assertions
Assertions are added after java 1.4 to always create reliable programs that are
Correct and robust programs. The assertions are Boolean expressions. Conditions such as
positive number or negative number are examples.
Syntax:
assert expression1;
or
assert expression1:expression2;
Where assert is the keyword. Expression 1 is the Boolean
expression, expression2 is the string that describes the
Exceptions.
Note: assertions must be explicitly enabled. The –ea option is used to enable the
exception and –da is used to disable the exception.
AI.java
import java.io.*;
class AI
{
void check(int i)
{
assert i>0:" I must be positive:";
System.out.println("Your I value is fine");
}
public static void main(String args[]) throws IOException
{
AI a=new AI();
a.check(Integer.parseInt(args[0]));
}
}}

You might also like