Interfaces


Interfaces: It is Java's way of dealing with the common situation of wanting a class to reflect the behavior of two (or even more) parents.

An interface is a skeleton of a class, showing the methods of the class, when someone implements it.

Interfaces provide abstract method definitions, you then have to implement those methods in your own classes, using the same method signatures as in the interface.

Java does not support multiple inheritance so it is achieved using Interfaces.

Interface declaration rules

It is similar to java class - counted as a valid reference type
Can not be instantiated - No object creation
No behavior - No method implementation
Declarations are always public - methods, variables even if you do not mention
Only constant data - final by default and static

Syntax for defining an Interface:
interface InterfaceName
{
  variable declaration;
  method declaration;
}

Here, interface is the keyword and interface name is any valid java variable (just like class name).

Example :
public interface Comparable
{
  public static final count = 9; // Variable should be declared final.
  public int compareTo(Object o); // method declaration should be public.
  public void print(); // method declaration.
}

Implementing the 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.

Syntax:
access class classname implements interfacename
{
  body of classname;
}

Here the access is public or not used, class classname implements the interface interfacename.
If a class implements more than one interface then the interfaces are separated by comma.
If a class implements two interfaces that declare the same method, then the same method will be used by the clients of both the Interfaces.
The methods that implement an interface must be declared public, also the type signature must match exactly the type signature specified in the interface definition.
It is both permissible and common for classes that implement interfaces to define additional members of their own.

public class Number implements Comparable
{
  public int compareTo(Object o)
  {
    //code for this method.
      .
      .
      .
  }
  public void print()
  {
    //code for this method.
      .
      .
      .
  }
}

Program

interface TestIntf
{
  public void disp();
}

class TestD implements TestIntf
{
  public void disp()
  {
    System.out.println(" I am Testing Interfaces");
  }
  void output()
  {
    System.out.println(" method of Impl class");
  }
}

class TestDisp1
{
  public static void main(String args[])
  {
    TestIntf t1;
    t1=new TestD();
    t1.disp();
  }
}

But since t1 is the object of Interface it will not be able to access the method output() of TestD. This program does it because t1 is object of TestD.

interface TestIntf
{
  public void disp();
}

class TestD implements TestIntf
{
  public void disp()
  {
    System.out.println(" I am Testing Interfaces");
  }
  void output()
  {
    System.out.println(" method of Impl class");
  }
}

class TestDisp
{
  public static void main(String args[])
  {
    TestD t1;
    t1=new TestD();
    t1.disp();
    t1.output();
  }
}

Click here for example.

More on Interfaces

A class can implement any number of interfaces:
class Number implements Comparable, Serializable, Cloneable {...}

An interface can extend any number of interfaces:
public interface Comparable extends Serializable,Cloneable {...}

Interface can be implemented by more than one class: So Polymorphism

interface AnimalInterface
{
	void breathing();
}

class animal implements AnimalInterface
{
	public void breathing()
	{
		System.out.println("\nBreathing from animal");
       	}
}

class fish implements AnimalInterface
{
	public void breathing() 	
	{
        	System.out.println("\nBubbling from fish");
        }
}
class DoubleImpl
{
	public static void main(String args[])
	{
        	AnimalInterface pet1=new animal();
        	AnimalInterface pet2=new fish(); 
        	pet1.breathing();
        	pet2.breathing();
        }
}

Uses of Interfaces

  • Interfaces can be used to specify the signature and it can be implemented by different classes in different way. So polymorphism can be achieved.
  • When you use interface type as parameter to a method then it is like passing in a subclass like an argument and having the correct overriding methods.
  • Since Interfaces declare constants they can be used globally. That is multiple classes can use them.

Nested classes

It is possible to define a class within another class; such classes are known as nested classes. The scope of the nested class is bounded by the scope of its enclosing class. Thus if class B is defined within class A, then B is known to A but not outside A. Nested class access to the members including the private members of the class in which it is nested. However enclosing class does not have access to the members of nested class.

Two types of nested classes. Static and non static. By applying access modifier a class can be made static.

Static: A nested top level class is a class which is defined inside another top level class as its static member. Since this class is declared as static only one copy of it is maintained for every instance of the enclosing class.

Inner classes

The most important type of nested class is inner class. An inner class is a non static nested class. Inner class access to the members including the private members of the class in which it is nested. However enclosing class does not have access to the members of nested class.-This kind of inner classes are also known as member class.

Program

class Outer
{
	int outer_i=101;
    	void test()	
	{
        	Inner inner= new Inner();
        	inner.display();
        }
//This is an inner class
	class Inner 
	{
		void display()
		{
      			System.out.println("display: outer_i="+outer_i);
		}
	}
}
class InnerClassDemo
{
	public static void main(String args[])
        {
       		Outer outer = new Outer();
        	outer.test();
	}
}

In the program given the Inner class has the access to Outer_i as discussed but the any member of the Inner class is not accessible to the outer class.

Local Class

It is also possible to declare inner class within the scope of any block. For example you can define a nested class within the block defined by a method or even within the body of a for loop.

class Outer
{
	int outer_i=101;
    	void test()
	{
       		for (int i=0; i<=6; i++)
           	{
    			class Inner
			{
    				void display()
				{
      					System.out.println("display: outer_i="+outer_i);
             			}
           		}
        		Inner inner= new Inner();
        		inner.display();
         	}

	}
}
class InnerClassDemo2
{
	public static void main(String args[])
	{
       		Outer outer = new Outer();
        	outer.test();
	}
}

Anonymous Class

This is the inner class which is not assigned with any name------
              will be discussed when we deal with applets.

Classification of Java classes - Schematic



The Properties that make inner class useful are

  • The inner class's name is not usable outside its scope, except perhaps in a qualified name.
  • This helps in structuring the classes within a package.
  • The code of an inner class can use simple names from enclosing scopes, including both class and instance members of enclosing classes, and local variables of enclosing blocks.

Abstract classes

Abstract class is an incomplete class that requires further specialization. An Interface is just a specification or prescription for behavior.


Java Streams << Previous

Next>> Java Applet

Our aim is to provide information to the knowledge


comments powered by Disqus








Footer1