Advertisement
//Java - Example of an interface
interface A
{
// Unlike regular methods, method of an interface
// should not be implemented within a pair of curly braces {} and,
// each method of an interface should end with a semicolon.
void getName();
}
//Java - Example of an interface
interface Math
{
void add(int a, int b); //add method is public and abstract by default
void subtract(int a, int b); //subtract method is public and abstract by default
}
//Java - Example of an interface
interface Math
{
void add(int a, int b);
void subtract(int a, int b);
}
//class A implementing Math interface
class A implements Math
{
public void add(int a, int b);
{
System.out.println(a+b);
}
public void subtract(int a, int b);
{
System.out.println(a-b);
}
}
//Java - Interface
interface A
{
int a = 10;
}
class B implements A //B class is implementing interface A, using implements keyword
{
public void m()
{
a = 20; //Trying to change the value of an inheritred interface constant, a
}
}
A.java:10: error: cannot assign a value to final variable a
a=20;
^
1 error
Advertisement
//Java - You cannot create an object of an interface
interface A
{
void methodA();
}
class B
{
public static void main(String... ar)
{
A ob = new A(); //instantiating an interface, throws a compile error.
}
}
A.java:10: error: A is abstract; cannot be instantiated
A ob = new A();
^
1 error
//Java - Example of Interface
interface A
{
void methodA();
}
interface B
{
void methodB();
}
//inteface C extending multiple interfaces without providing implementation of their methods
interface C extends A,B
{
}
//Java - Example of Interface
interface A
{
void methodA();
}
interface B
{
void methodB();
}
interface C
{
void methodC();
}
//class D is implementing interface A, B and C
class D implements A,B,C
{
public void methodA() //providing implementation of methodA() of interface A
{
System.out.println("A");
}
public void methodB() //providing implementation of methodB() of interface B
{
System.out.println("B");
}
public void methodC() //providing implementation of methodC() of interface C
{
System.out.println("C");
}
}
//Java - Example of Interface
interface Math
{
void add(int a, int b); //add method signature
void subtract(int a, int b); //subtract method signature
}
abstract class A implements Math
{
}
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement