adspace
what is interface in java ?can you explain with simple
example?and what is the difference between abstract and
interface?
Answer Posted / Bholendra Pratap Pandey
In Java, an Interface is a collection of abstract methods (methods without a body) and constant variables (variables whose values cannot be changed). It defines a set of rules that a class implementing the interface must follow. Here's an example of an interface:
```java
interface Shape {
double PI = 3.14;
void draw();
}
```
A class can implement an interface by providing a concrete implementation for its abstract methods:
```java
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public void draw() {
// draw code for circle goes here
}
}
```
An Abstract class, on the other hand, can contain both abstract and concrete methods. It provides a partial implementation of the rules and leaves some parts to be implemented by the subclass:
```java
abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public abstract void makeSound();
public void introduce() {
System.out.println("My name is " + name);
}
}
```
In summary, an interface declares a contract that the implementing class must adhere to (methods and constants), while an abstract class can have both concrete and abstract methods to provide a base structure for its subclasses.
| Is This Answer Correct ? | 0 Yes | 0 No |
Post New Answer View All Answers