Java With Us
Home   |   Tutorial   |   Programs  

Java Tutorial

Introduction to Java
Hello World Program
Variables and Data types
More about data types
Displaying text using print and println
Displaying text using printf
Java Comments
Naming conventions for Identifiers
Mathematical operations in Java
Taking input from the user

Classes and Objects
Introduction to object oriented programming
The constituents of a Class
Creating objects and calling methods
Get and Set Methods
Default constructor provided by the compiler
Access Specfiers
Scope and lifetime of Variables
Call by value and Call by Reference

A few more topics
Casting
Class as a reference data type
Constants or literals
Final variables
Increment and decrement operators
Manipulating Strings
Operators
Overloading constructors and methods
Static methods and variables
The Java API
The Math class
this keyword
Wrapper classes

Control Structures
Control Statements
Repetition statements
Nested loops
Formulating algorithms
Branching Statements

Arrays
Arrays introduction
Processing arrays using 1oops
Searching and sorting arrays
Array of objects
Multi dimensional arrays
Taking input as command line arguments
Using ellipsis to accept variable number of arguments

Inheritance
Inheritance introduction
Relation between a super class and sub class
Final classes and methods
The protected access specifier
Class Object

Polymorphism
Introduction
Interfaces
Packages
Abstract classes and methods

Exception handling
Exception handling introduction
Exception hierarchy
Nested try catch blocks
Throwing exceptions


Interfaces

A Java interface is used to specify what is to be done but not how it is to be done. For example, a Vehicle should be capable of performing several tasks such as starting, stopping and changing speed. All types of vehicles, be it a car or an aeroplane should be capable of doing these tasks. In such a case, we can define an interface Vehicle where these various methods are specified but the definition of these methods are given in the classes like Car and Aeroplane which implement these interfaces.

A Java interface consists of only final static variables and abstract methods. No implementation is provided for the methods. We may declare the vehicle interface in the following way:

public interface Vehicle {
    // body
}

The interface name follows conventions similar to those followed by class names. The first letter of each word in an interface is capitalised. The access specifier may be either public or unspecified. When stated as public, the interface is available to all classes. When no access specifier is stated, default access restrictions are applied and the interface is accessible only from classes within the same package. private and protected access specifiers cannot be used here. The interface may not be private because it should be accessible from other classes if they are to implement. On similar lines, the use of protected is absurd since an interface is mainly defined to be implemented in a class and there exists no such thing like a class inheriting an interface because of which protected would offer the same level of protection as the package specifier. Hence, its use is absurd.

The interface may contain both variables and methods. Variables are implicitly final, static and public. And the methods are implicitly abstract and public. Use of specifiers that overwrite these default specifiers is not allowed. For example, both methods and variables may not be declared with the public or protected specifiers. The reason behind this is the same as discussed above with reference to the interface.

The following example shows the interface Vehicle with three abstract methods and a final variable code.

public interface Vehicle {

    int CODE = 347; // implicitly public and final
    void start(); // method is implicitly public and abstract
    public void stop(); // method is implicitly abstract
    public abstract void changeSpeed(int newSpeed);
}

Note that the variables declared in an interface should be initialised with default values as final variables require that they be initialised at the time of declaration itself. A class which implements this interface should provide the definition for all of the abstract methods. Given below is an example.

public class Aeroplane implements Vehicle {

    int speed;

    public void start() {
        System.out.println(" Taking off");
    }

    public void stop() {
        System.out.println(" Taking landing");
    }

    public void changeSpeed(int s) {
        speed = s;
    }
}

Note that the variable names used in the parameter list of the method name in this class and those defined in the interface need not match as was the case always. We have used the variable name s instead of newSpeed.

The @Override annotation may be used here too to ensure that we are using the correct method definition.

A statement like the following would be valid since the variable CODE is now a part of the class Aeroplane too as the interface Vehicle containing the variable CODE has been implemented.

System.out.println(CODE);

Even a class that does not implement an interface can access the variables defined in the interface since they are static.

int code= Vehicle.CODE;

A class can implement more than a single interface. These interfaces are included in the class declaration with a comma separated list as shown below.

public class Aeroplane implements Vehicle, AnotherInterface {
}

Moreover, a class can define its own additional variables, methods and constructors just like any other class. Also it can extend a superclass in addition to implementing the interfaces. An interface can also be implemented by more than a single class.

If a class does not provide the implementations of all the methods declared in the interface, the class itself should be defined as abstract. These abstract methods can then be defined in classes which extend it.

An interface also works as a data type. Though objects of an interface cannot be created, we can assign to the variable a reference of an object belonging to a class which implement the. For example, we can assign the reference of an Aeroplane object to a Vehicle variable.

Vehicle v = new Aeroplane();

The above statement indicates that there is an 'is a ' relationship between the class the implementing classes and the interface and hence the following applications and results.

public Vehicle meth() {
return new Aeroplane();
}

public void someMethod( Vehicle v ) {
//code
}

// call to the above method
someMethod( new Aeroplane() );

// use of instanceof
Aeroplane a=new Aeroplane();
Boolean b=a instanceof Vehicle; //true

The above technique of considering an interface as a data type brings out the reason behind the use of an interface. One can code a class containing calls to start() and stop() on vehicle objects unbothered about the type of Vehicle- an Aeroplane or a Car. Since only objects of types that have implemented the Vehicle interface can be passed to the class, there is no need to worry if the class has the methods start() and stop(). However, to use method other than those defined in the interface, the object needs to be cast to an appropriate type. For example, consider that the Aeroplane class has an additional method flyHigher(). This method called be invoked on an object through a variable of type Vehicle only after explicitly casting it.

Vehicle v=new Aeroplane();
v.flyHigher(); // compilation error

This is because the interface Vehicle hasn't declared a flyHigher() method. To be able to call this method, the object needs to first cast to an Aeropalne.

Aeroplane a=(Aeroplane) v;
a.flyHigher();

Interfaces can also be extended just like classes using the extends keyword. But unlike classes, an interface can extend more than one interface by using a comma separated list.

public interface SuperVehicle extends Vehicle {
// code
}

The new interface will also posses all the variables and methods declared in its super interfaces.

Inheritance is generally in the context of interfaces when extending an interface is necessary. For example, consider that the above Vehicle() interface has been implemented by many other developers. Now, if you add another method to this interface, all the classes created by the other developers would break as a class when implementing an interface should provide definitions for all the methods that have been declared in the interface. The developers will have to modify their classes before they can be used once gain. To avoid such complication, interfaces are extended when one wishes to modify them by adding new methods.

Privacy Policy