An interface is a collection of abstract methods (methods without an implementation) and constants. An interface can be used to define a set of methods that a class must implement, without specifying how those methods are implemented.
To declare an interface in Java, you use the interface
keyword followed by the name of the interface.
interface Car {
public void operationA();
public void operationB();
}
interface Bike {
public void lights();
}
class ModelA implements Car, Bike {
public void operationA() {
System.out.println("Operation A");
}
public void operationB() {
System.out.println("Operation B");
}
public void lights() {
System.out.println("Generic Lights Starts");
}
}
public class Main {
public static void main(String[] args) {
ModelA firstObj = new ModelA();
firstObj.operationA();
firstObj.operationB();
firstObj.lights();
}
}
This code defines an interface Car
with two abstract methods operationA()
and operationB()
. It also defines another interface Bike
with one abstract method lights()
.
interface Car {
public void operationA();
public void operationB();
}
interface Bike {
public void lights();
}
Next, a class named ModelA
is defined that implements both the Car
and Bike
interfaces. This class provides the implementation of all the abstract methods declared in the interfaces it implements.
class ModelA implements Car, Bike {
public void operationA() {
System.out.println("Operation A");
}
public void operationB() {
System.out.println("Operation B");
}
public void lights() {
System.out.println("Generic Lights Starts");
}
}
The operationA()
method of ModelA
class simply prints "Operation A" to the console. The operationB()
method of ModelA
class prints "Operation B" to the console. The lights()
method of ModelA
class prints "Generic Lights Starts" to the console.
Finally, in the main()
method of the Main
class, an instance of the ModelA
class is created and the methods operationA()
, operationB()
, and lights()
are called on it.
public class Main {
public static void main(String[] args) {
ModelA firstObj = new ModelA();
firstObj.operationA();
firstObj.operationB();
firstObj.lights();
}
}
This code demonstrates how a class can implement multiple interfaces and provide implementation for all the methods declared in them. It also demonstrates how objects of a class can be created and methods can be called on them.
No comments:
Post a Comment