Interface in java

 Java Interface


    We use interface keyword for creating java interfaces. An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class.

    Interface is look like a class. Its runs like normal class. But we cant create objects to the interface. We can create object using upcasting. Old days we cant create constructors for interface. But nowadays we can create constructors for interface(After java 8).

    We can create meaningless methods(abstract method) in interface for overriding. After java 8, we can hold normal methods also in interface.

    In a interface can not have normal variables (int a=5). But in a interface can have variables using static(can access without creating objects) and final(cannot change values after assigning)  type(static final int a=10 , static final String a="name").After java 8, we can have normal variables also.



    We cant create multiple inheritance(extends) to normal class.


  
      Interface provides a way to achieve abstraction and multiple inheritance in Java. We use implements keyword to inherit interface to the classes.

    Inside the interface, static, final, and private methods declaration are not possible.
In Interface only one specifier is used- Public.

    Inside the interface main method is not allowed.


Example code:-

Advantages of java interface:-

  • Interfaces allow for abstraction by defining a set of methods without specifying their implementation details.
  • In Java, multiple inheritances are not allowed, however, you can use an interface to make use of it as you can implement more than one interface.
  • By providing a common set of methods that can be implemented by multiple classes, interfaces promote code reusability.

    Interfaces remain a powerful tool in Java development, and their disadvantages are often outweighed by the benefits they bring to code organization, flexibility, and maintainability. It's crucial to use interfaces judiciously and consider the specific needs of the application or system being developed.

Difference between classes and interface in java:-





Comments

Popular posts from this blog

අද අපි කතා කරමු Data collections ගැන

Understanding and Mastering Coding Errors

OOP key points