Skip to main content

Concept of Interface

We have learned about classes in packages and next to it is the implementation of interface in java programming. An interface in Java programming language is an abstract type, which is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations in variable declarations that are declared to be both static and final keywords. All methods of an Interface do not contain implementation.

Interfaces cannot be instantiated, but rather implemented. A class that implements an interface must implement all of the methods described in the interface, or be an abstract class.

Engineering Study Material One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object the root class.

A Java class may implement an interface and may extend to any number of interfaces; however an interface may not implement an interface. Also, java programming language does not support multiple inheritances. Using interfaces we can achieve this as a class can implement more than one interfaces, however it cannot extend more than one classes.

For example:
Declaration of Interface with syntax:
interface My Interface
{
/* All the methods are public abstract by default
* Note down that these methods are not having body
*/
public void method1();
public void method2();
}

Program on sample interface:
interface Bounceable
{
void setBounce(); // Note the semicolon
// Interface methods are public, abstract and never final.
// Think of them as prototypes only; no implementations are allowed.
}

Defining an interface
Interfaces are defined with the following syntax (compare to Java's class definition):
interface InterfaceName [extends other interfaces]
{
constant declarations
abstract method declarations
}
The body of the interface contains abstract methods. Since all the methods in an interface are by definition abstract so the abstract keyword is not required in specific. Since the interface specifies a set of exposed behaviours, all methods are implicitly public.
Thus, a simple interface may be
public interface worker
{
boolean dowork(Work w);
void earnmoney(Work w);
}
The member type declarations in an interface are implicitly static, final and public, but otherwise they can be any type of class or interface.
The syntax for implementing an interface uses this formula:
... implements InterfaceName[, another interface, another, ...] ...
Classes may implement an interface.

For example,
public class Lion implements Predator
{
@Override
public boolean dowork(work w)
{
// programming to work w (In case of daily worker)
}
@Override
public void earnmoney(Work w)
{
// programming to earnmoney Work w
}
}
If a class implements an interface and does not implement all its methods, it must be marked as abstract. If a class is abstract, one of its subclasses is expected to implement its unimplemented methods. Although if any of the abstract class' subclasses do not implement all interface methods, the subclass itself must be marked again as abstract.

Example program on interface:
Simple example of Java interface
In this example, printable interface have only one method, its implementation is provided in the B class.
interface printable
{
void print();
}
class B2 implements printable
{
public void print()
{
System.out.println("Welcome to learn Interface concept in core java");
}
public static void main(String args[])
{
B2 obj = new B2();
obj.print();
}
}
Execution:
Output: Welcome to learn Interface concept in core java

Interface Implementation
Before you can really use an interface, you must implement that interface in some class. Here is a class that implements the MyInterface interface shown above
Syntax:
public class MyInterfaceImpl implements MyInterface
{
public void sayHello()
{
System.out.println(MyInterface.hello);
}
}
Notice the implements MyInterface part of the above class declaration. This signals the Java compiler that the MyInterfaceImpl class implements the MyInterface interface.

A class that implements an interface must implement all the methods declared in the interface. The methods must have the exact same signature (name + parameters) as declared in the interface. The class need not to implement (declare) the variables of an interface instead only methods.

This is how a class implements an interface. It has to provide the body of all the methods that are declared in interface.

Here mainly Class implements interface but an interface extends another interface.

File name : MammalInt.java
public class MerecedsInt implements Car
{
public void start()
{
System.out.println(“Start the vehicle");
}
public void travel()
{
System.out.println(" vehicle travels");
}
public int noOftries()
{
return 0;
}
public static void main(String args[])
{
MerecdesInt m = new MerecdesInt();
m.start();
m.travel();
}
}

Execution Output:
Merecdes eats
Merecdes travels

Example Program on implentation:
interface MyInterface
{
public void method1();
public void method2();
}
class XYZ implements MyInterface
{
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new XYZ();
obj. method1();
}
}
Output:
implementation of method1

Examples of java implementations:
public abstract class Vegetable
{
*/////////////
}
public class Tomato extends Vegetable
{
*////////////
}

Interface inheritance
When a class extends another class it is called inheritance. The class that extends is called sub class while the class that is extended is called super class. Any class in java that does not extend any other class implicitly extends Object class.

By means of inheritance a class gets all the public, protected properties and methods of the super class, no matter which package the sub class is present in. If the sub class is present in the same package as that of super class then it gets the package private properties and methods too. Once the sub class inherits the properties and methods of super class, it can treat them as if it defined them.

By using inheritance you can reuse existing code. If you have an already written class (but no source) and it lacks some features then you don’t have to write everything from scratch. Just extend the class and add a new method that satisfies your needs
Engineering Study Material
Sample Program
Use extends keyword to inherit the super class-
class A
{
//properties and methods of A
}
class B extends A
{
*////////////////////
}

Method Overriding and Hiding:
Method overriding in object oriented programming, is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class, only if a method is declared virtual then derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.

Sample Program:
class Thought
{
public void message()
{
System.out.println("I feel like I am diagonally parked in a parallel universe.");
}
}
publicclass Advice extends Thought
{
@Override // @Override annotation in Java 5 is optional but helpful.
public void message()
{
System.out.println("Warning: Dates in calendar are closer than they appear.");
}
}
Class Thought represents the superclass and implements a method call message(). The subclass Advice inherits every method that could be in the Thought class. However, class Advice overrides the method message(), replacing its functionality from Thought.

Exceution:
Thought parking = new Thought();
parking.message(); // Prints "I feel like I am diagonally parked in a parallel universe."

Thought dates = new Advice(); // Polymorphism
dates.message(); // Prints "Warning: Dates in calendar are closer than they appear."

Method over loading in java:
In same class, if name of the method remains common but the number and type of parameters are different, then it is called method overloading in Java.
There are nine different ways the print method of the System.out object can be used.
  • print.(Object obj)
  • print.(String s)
  • print.(boolean b)
  • print.(char c)
  • print.(char[] s)
  • print.(double d)
  • print.(float f)
  • print.(int i)
  • print.(long l)
When you use the print method in your code the compiler will determine which method you want to call by looking at the method signature.

For example:
int number = 9;
System.out.print(number);
String text = "nine";
System.out.print(text);
boolean nein = false;
System.out.print(nein);
Each time a different print method is being called because the parameter type being passed is different. This comes handy at times when the print method will need to vary dynamically depending on whether it has to deal with a String or integer or boolean.
Example program:
class overLoading
{
public static void main(String[] args)
{
functionOverload obj = new functionOverload();
obj.add(1,2);
obj.add(\"Life at \", \"?\");
obj.add(11.5, 22.5);
}
}
class functionOverload
{
/* void add(int a, int b) // 1 - A method with two parameters
{
int sum = a + b;
System.out.println(\"Sum of a+b is \"+sum);
} */
void add(int a, int b, int c)
{
int sum = a + b + c;
System.out.println(\"Sum of a+b+c is \"+sum);
}
void add(double a, double b)
{
double sum = a + b;
System.out.println(\"Sum of a+b is \"+sum);
}
void add(String s1, String s2)
{
String s = s1+s2;
System.out.println(s);
}
}
Published date : 14 Feb 2015 03:01PM

Photo Stories