Skip to main content

Interfaces in java with example

Interface concept included in java to overcome the Diamond problem of multiple inheritance in java. In other words, Interface was introduced in java to define objects outside the world through methods. For example, buttons on the front of the television set. That are the interfaces between you and the electrical set. You press the power button to turn the television to on or off.

An interface is a specification of method prototypes. Prototypes will be in the interface. All the methods of the interface are abstract. For the polymorphic interface inheritance, where the client wants to only deal with a type and does not care about the actual implementation use interfaces. If you need to change your design frequently, you should prefer using interface to abstract class.

Through interfaces we can achieve multiple inheritance in java. Because there is a possibility of inheriting more than one interface into java class by using the keyword called implements. When we try to inherit from one interface to another interface we must use extends keyword like classes.

In interfaces we have to define the method declaration only. It will not allow to implement methods inside the interfaces. The method implementation/declaration should be present in the class which has implements the interface. The class which contains method implementation called as subclass / child class of the interface.

Here is the example interface with the name called Vehicle with few of the unimplemented methods.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package com.javatbrains.interfaces;

public interface Vehicle {
    
     void changeGear(int newValue);

     void speedUp(int increment);

     void applyBrakes(int decrement);
}

To implement the interface methods we have to create a class which will implements the interface. To implement the interface, will use the implements keyword in java. The below is the Car class which will implements the Vehicle interface. The methods in the Car class will contains @Override annotation on top of the method. Those methods are called overridden methods. Along with overridden methods, subclass will contains it's own methods. Those methods are not declared with the @Override annotation.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.javatbrains.interfaces;

public class Car implements Vehicle {
     int speed = 0;
     int gear = 1;

     @Override
     public void changeGear(int newValue) {
          gear = newValue;
     }

     @Override
     public void speedUp(int increment) {
          speed = speed + increment;
     }

     @Override
     public void applyBrakes(int decrement) {
          speed = speed - decrement;
     }

     void printStates() {
        System.out.println(" speed: " +
            speed + " gear: " + gear);
   }

}

Implementing an interface allows a class to become more formal about the behaviour it promises to provide. When you are implementing an interface into a class that class should override the interface methods into implementing class. Otherwise compiler will complain.

Key points in interfaces:
  • An interface is a specification of method prototypes.
  • An interface contains 0 or more abstract methods.
  • All the methods of the interface are public and abstract by default.
  • An interface may have variables, which are public static final by default. In other words, interfaces can declare only constants, not instance variables.
  • We can not create an object for interfaces.
  • But we can create a reference of interface type.
  • All the abstract methods of the interface should be implemented in its implementation class.
  • I nterface reference can be used to refer to the objects of implementation classes.
  • If any method is not implemented in an implementation class, class should be declared as "abstract".
  • Once an interface is written, any third party vendor can implement it.
  • An interface cannot implement another interface.
  • An interface can extends another interface.
  • We can write a class inside an interface.
  • A class can implements multiple interfaces.
  • All the methods are incomplete only.
  • Interface methods must not be static. Because interface methods are abstract, they can not be marked final, strictfp, native.
  • Interface does not have constructors. Interfaces are not part of an object's inheritance tree.
Here is the another example of one interface is implementing more than one class.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.javatbrains.interfaces;

interface DbConnection {
     void connect(); // public abstract
}

class OracleConnection implements DbConnection {

     @Override
     public void connect() {
          System.out.println("Connecting to Oracle database");
     }

}

class SybaseConnection implements DbConnection {

     @Override
     public void connect() {
          System.out.println("Connecting to Sybase database");
     }

}

class MySQLConnection implements DbConnection {

     @Override
     public void connect() {
          System.out.println("Connecting to MySQL database");
     }

}

public class Database {

     public static void main(String[] args) throws Exception {
          // Accepts the database name and store it in object c
          Class c = Class.forName(args[0]);
          // Create an object to the class whose name is in c
          DbConnection connection = (DbConnection) c.newInstance();
          connection.connect();
     }

}

What is marker interface?
          Marker interface is an interface, which doesn't contains any of the methods. But, still that type of interfaces are doing their functionality. For example, Serializable, Cloneable..etc.

Do you Know?

Comments

Post a Comment

Popular posts from this blog

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...

Prime, Fibonacci and Factorial number with example in java

Prime number, Fibonacci series and Factorial number programs are most commonly asked questions in interview. Read this article to know what is and how to write programs for prime number, fibonacci series and factorial number. Prime Number: prime number is natural number greater than 1 that has no positive divisor other than 1 and itself. A natural number greater than 1 is not a prime number, is called Composite number . For example, 7 is a prime number. Because it can divide with 1 and 7 only. Where as 8 is composite number. Since it has the divisor 2 and 4 in addition to the 1 and 8. The below example represents the finding the passing number is prime number or not. If the passing number is prime number it will print true otherwise it will print false. package com . javatbrains . practice ; public class PrimeNumber { public boolean isPrimeNumber ( int number ) { if ( number <= 1 ) return false ; // There's only one ...

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...