Can we create an object for an interface?
In some programming languages, interfaces define a contract for the methods that a class must implement, but they cannot be directly instantiated like classes. Instead, you need to create a class that implements the interface, and then you can create an object of that class.
For example, in Java:
```java
// Define an interface
interface MyInterface {
void myMethod();
}
// Implement the interface in a class
class MyClass implements MyInterface {
@Override
public void myMethod() {
System.out.println("Implemented method");
}
}
public class Main {
public static void main(String[] args) {
// Create an object of the class that implements the interface
MyClass myObject = new MyClass();
// Call the method defined in the interface
myObject.myMethod();
}
}
```
In this example, `MyClass` implements the `MyInterface` interface, and an object of `MyClass` is created and used. The key point is that you can create objects of classes that implement the interface, but you cannot directly instantiate an object of the interface itself.
Comments
Post a Comment