Enter your keyword

post

Java Interface

Definition


An interface in Java is similar to a class, but the body of an interface can include only abstract methods and final fields (constants). A class implements an interface by providing code for each method declared by the interface.

Example

/* File name : MammalInt.java */
public class MammalInt implements Animal{

public void eat(){
System.out.println("Mammal eats");
}

public void travel(){
System.out.println("Mammal travels");
}

public int noOfLegs(){
return 0;
}

public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

Commonly asked interview questions on Constructors

1.What is an interface in Java.

Answer :A class that implements an interface is compelled to implement all the methods that have been declared in the interface.

For a class to successfully compile, it should have implemented all the methods in the interface. This way, the interface makes the behavior of the class formal by defining its behaviour.

2.What will happen if we define a concrete method in an interface?

Answer :By default interface methods are abstract.
if we declare any concrete method in an interface compile time error will come.
Error:Abstract methods do not specify a body

3.Can we create non static variables in an interface?

Answer :No.We can not create non static variables in an interface.
If we try to create non static variables compile time error comes.
By default members will be treated as public static final variables so it expects some value to be initialized.

4.What will happen if we not initialize variables in an interface.

Answer :Compile time error will come because by default members will be treated as public static final variables so it expects some value to be initialized.
package com.instanceofjava;
interface JavaInterface{

int x, y; // compile time error: The blank final field y may not have been initialized

}

5.When we need to use extends and implements?

Answer :
A class will implements an interface.
A class will extends another class.
An interface extends another interface.

Take Sample Test

Reference Books


1. Head First Java

No Comments

Add your review

Your email address will not be published.