In this video, I have given an introduction to interface in java. Java interface is one of the most important topic from where interviewers asks questions.
INTRODUCTION OF INTERFACE
An interface is basically a kind of class. Like class, interface also contains methods and functions but a difference that it can only contain abstract methods and final fields.
1) Abstract Methods – This is a method that is declared without an implementation (without braces and implementation)
Eg: void display(); := declaration
void display() := definition
{
------- -------
------ --------
}
2) Final Fields – A final fields cannot change its value
INTRODUCTION OF INTERFACE
As we know that an interface only contains abstract method, hence it is responsibility of the class which is implementing this interface to define the method.
As we know that java does not support multiple inheritance. In order to do something like multiple inheritance, interface is used. That means in simple language we can say that interface is used to implement the concept of multiple inheritance in java.
Syntax for defining an interface:
interface interface_name
{
variable declaration;
method declaration;
}
Example for defining an interface:
interface values
{
static final int code=10;
static final String name=“hello”;
void display();
}
Extending Interfaces:
In the same way we extends a class. We can also extend an interface. It means that an interface can extend another interface.
Syntax:
interface name1 extends name2
{
body of name1;
}
Example:
interface abc
{
int code=101;
String str=“Anup”;
}
interface xyz extends abc
{
void display();
}
Implementing Interfaces
Interfaces are actually made for performing the work of a super class. It is a way to implement multiple inheritance in java.
Syntax:
class classname implements interfacename
{
body of the class
}
Syntax:
class classname extends superclass implements interfacename
{
body of the class
}
Program :-
interface area
{
final static float pi=3.14F;
float calculate(float x,float y);
}
class rectangle implements area
{
public float calculate(float x,float y)
{
return x*y;
}
}
class circle implements area
{
public float calculate(float x,float y)
{
return pi*x*x;
}
}
class demointerface
{
public static void main(String[] args)
{
rectangle rect=new rectangle();
circle cir=new circle();
area a;
a=rect; //rect class reference
System.out.println("Area of Rectangle="+a.calculate(10,20));
a=cir; // circ class refererence
System.out.println("Area of Circle="+a.calculate(10,0));
}
}
#technicalicode
#interfaceinjava
#javainterface
#interfaces
In questa pagina del sito puoi guardare il video online Introduction to Interface in Java | Interface Methods | Java Interface Class | What is Interface della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Technical Icode 31 agosto 2023, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 13 volte e gli è piaciuto 0 spettatori. Buona visione!