Skip to main content

JAVA Interface

What is it?
  1. Java interface is a bit like a class, except you can only declare methods and variables in the interface. You cannot actually implement the methods. It is a collection of abstract methods.
  2. Interfaces are a way to achieve polymorphism in Java.
  3. Interface is declared using the Java keyword interface.
  4. Interface can be declared public or package scope (no access modifier).
  5. If the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.
  6. When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.
  7. A class can implement more than one interface at a time.
  8. The methods must have the exact same signature (name + parameters) as declared in the interface. The class does not need to implement (declare) the variables of an interface only the methods. 
Interface Structure:
public interface NameOfInterface{
   //Any number of final, static fields
   //Any number of abstract method declarations
}
Interface Instance:
Once a class implements an interface you can use an instance of that class as an instance of that interface. Here is an example:
public interface MyInterface {
    public String hello = "Hello";
    public void sayHello();
}
public class MyInterfaceImpl implements MyInterface {
    public void sayHello() {
        System.out.println(MyInterface.hello);
    }
}
public class Test{
         public void static main(String[] args){
         MyInterface myInterface = new MyInterfaceImpl ();
         myInterface.sayHello();
         }
}

Explanation: The variable ‘myInterface’ is declared to be of the “MyInterface” interface type while
 the object created is of type “MyInterfaceImpl”. This is possible because the class “MyInterfaceImpl”   implements the “MyInterface” interface. You can then reference instances of the “MyInterfaceImpl”   class as an instance of the “MyInterface” interface. You cannot create instances of an interface by  itself. You must always create an instance of some class that implements the interface, and reference to that instance as an instance of the interface.

Interface Importing:
If the interfaces are not located in the same packages as the implementing class, you will need to import the interface. Interfaces are imported just like classes. For instance:
import com.test.package1.MyInterface;
import com.test.package2.YourOtherInterface;
public class MyInterfaceImpl implements MyInterface, MyOtherInterface {
    ...
}
Interface Properties:
  1. An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface. 
  2. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. 
  3. Methods in an interface are implicitly public.
Rules for overriding methods defined in an Interface:
  1. Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.
  2. The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.
  3. The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.
Examples:
Example#1 Declare simple interface with one variable
public interface SimpleInf {
       public int x = 20;
}


Example#2 Declare simple interface with method
public interface SimpleInf {
       public void Hello();
       public String Bye();
}
Example#3 Implement an interface
In order to use an interface, you must implement that interface in some class.
public interface SimpleInf {
       public void Hello();
}
public class MyInterfaceImpl implements SimpleInf {
       public void Hello () {
       System.out.println(“Hello Dude !!”);
    }
Example#4 Interface extends another interface
The “extends” keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.
public interface Animals
{
   public void setAnimalSpeed();
   public void setAnimalTests();
}
//Filename: setAnimalSound.java
 public interface setAnimalSound extends Animals
{
   public void analysesound();
   public void soundfrequency();
//Filename: setAnimaldetails.java
 public interface setAnimaldetails extends Animals
{
   public void animalweight();
   public void animalname();
   public void animalcolor(String color);
   public void animalcountry(String country);
}
Note: The “setAnimaldetails” interface has four methods, but it inherits two from “Animals”; thus, a class that implements “setAnimaldetails” needs to implement all six methods. Similarly, a class that implements “setAnimalSound” needs to implement the two methods from “setAnimalSound” and the two methods from “Animals”.

Example#5 Interface extends multiple interfaces
The “extends” keyword is used once, and the parent interfaces are declared in a comma-separated list.
public interface Animals
{
   public void setAnimalSpeed();
   public void setAnimalTests();
}
//Filename: AnimalShelterStatistics.java
 public interface AnimalShelterStatistics
{
   public void numberofcompanion(int number);
   public void costtoroundup(int cost);
}
//Filename: setAnimaldetails.java
 public interface setAnimaldetails extends Animals, AnimalShelterStatistics
{
   public void animalweight();
   public void animalname();
   public void animalcolor(String color);
   public void animalcountry(String country);
}
Note: The “setAnimaldetails” interface has four methods, but it inherits two from ‘Animals” and two from ‘AnimalShelterStatistics”; thus, a class that implements “setAnimaldetails” needs to implement all eight methods.

Interfaces and Polymorphism:
Interfaces are a way to achieve polymorphism in Java. This can be done through one of two ways.
The first way: Create new instance of interface and assign to it an instance of the implemented class for that interface. Example:
public interface MyInterface {
    public void sayHello();
}
public class MyInterfaceImpl implements MyInterface {
    public void sayHello() {
        System.out.println(MyInterface.hello);
    }
}
public class Test{
         public void static main(String[] args){
                MyInterface myInterface = new MyInterfaceImpl ();                 
                myInterface.sayHello();  
         }
}
The second way: Create new instance of the implemented class and cast it to an instance of the interface type. Example:
//The interface
public interface MyInterface {
    public void sayHello();
}
//The class which implements (inherit from) the interface
public class MyInterfaceImpl implements MyInterface {

    public void sayHello() {
        System.out.println(MyInterface.hello);
    }
}
//The Test class which will execute the above class and its implemented interface
public class Test{
         public void static main(String[] args){
         //create new instance of the class which implement the interface
         MyInterfaceImpl m1 = new MyInterfaceImpl();
         //Define a type of the interface and cast the class instance to it
         MyInterface myInterface = (MyInterface) m1;
         //Call the implementation of the method
                myInterface.sayHello();              
         }
}
What is the difference between Interface and class?
Interface
Class
An interface contains behaviors that a class implements.
A class describes the attributes and behaviors of an object
Cannot instantiate an interface
Can instantiate a class
An interface does not contain any constructors
A class contains constructors.
All of the methods in an interface are abstract implicitly. Which means all methods in an interface must be implemented in the calling class
Not necessary
An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final
A class contains instance fields
An interface is not extended by a class; it is implemented by a class using implements keyword
A class extends a class using extends keyword
An interface can extend multiple interfaces using extends keyword. Multiple inheritance is allowed
A class can extend only one class (parent class) using extends keyword. Multiple inheritance is not allowed


What is the Similarity between Interface and class?
Interface
Class
An interface can contain any number of methods
A class can contain any number of methods
An interface is written in a file with a .java extension, with the name of the interface matching the name of the file
A class is written in a file with a .java extension, with the name of the class matching the name of the file
The bytecode of an interface appears in a .class file
The bytecode of a class appears in a .class file
Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name
Classes appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name

Tagging Interface:
  • An interface with “no methods in it” is referred to as a tagging interface. Example:
    • public interface EventListener{}
  • There are two basic design purposes of tagging interfaces:
    • Creates a common parent
        • EventListener” interface is extended by dozens of other interfaces in the Java API; you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends “EventListener”, the JVM knows that this particular interface is going to be used in an event delegation scenario.
o   Adds a data type to a class
        • The term tagging comes from here. A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism.
Some notices:
  1. Avoid putting variables in interfaces if you can.
  2. All variables and methods in an interface are public, even if you leave out the public keyword in the variable or method declaration.
  3. Interfaces provide a cleaner way of implementing cross cutting functionality in classes than inheritance.




Comments

Popular posts from this blog

Error Class names are only accepted if annotation processing is explicitly requested

Do you get the following error? Class names, 'Hello', are only accepted if annotation processing is explicitly requested 1 error In case you got this error, then you forget to add .java to the file name when you compile it So when you want to compile a file using cmd console window write the filename.java extension Example: Javac Hello.java If you write it in this way the error will go away. So don’t forget to include suffix with your file name during compilation.

An attempt was made to insert a node where it is not permitted

Do you face this Error while you are writing code to generate xml file from java? Exception in thread "main" org.w3c.dom.DOMException : HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.        at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.insertBefore(Unknown Source)        at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(Unknown Source)        at generatexml.WriteXMLFile.main( WriteXMLFile.java:30 ) Well the answer is: Don't insert the node where it isn't permitted. Change your generated directory file path from 'C' to other directory ex, D or to any directory you have. Make sure the ‘appendChild’ is referring to the right element. Don’t appending twice, only make it once. Ex, //Writetoxml.java   Element rootElement = doc . createElement ( " Company " );   doc . appendChild ( ro...

Multitenancy

What is Multitenancy? Multitenancy is an architecture in which a single instance of a software application serves multiple customers. It gives the ability to use the same software and interfaces to configure resources and it isolates customer-specific traffic and data. Each customer is called a tenant. Tenants may be given the ability to configure some parts of the application, such as color of the user interface ( UI ) or business rules , but they cannot change the application's code . This means that although tenants are using the same building blocks in their configuration, the appearance or workflow of the application may be different for two tenants. Also, the Service Level Agreement (SLA) of each tenant can differ [1]. Multitenancy vs. Singletenancy: Multitenancy can be economical because software development and maintenance costs are shared. It can be contrasted with single-tenancy, an architecture in which each customer has their own software instance and ...