MCS024 : Question 3 (c) Define Interface & Implementing Two Interfaces in a Class | June 2023 Paper Solution

mcs024 june 2023 Paper

Question 3 (c) What is an Interface ? Write a java program to show how a class implements two interfaces.


Answer:

Interface in Java:
In Java, an interface is a collection of abstract methods that define a contract for classes to implement. It serves as a blueprint for classes, specifying the methods they should implement without providing any implementation details. An interface can also contain constant fields and default methods. By implementing an interface, a class promises to provide the defined behavior specified by the interface.

Java Program: Implementing Two Interfaces in a Class/Implementing Multiple Interfaces 

// First interface
interface Printable {

void print();
}

// Second interface
interface Displayable {
void display();
}

// Class implementing both interfaces
class MyClass implements Printable, Displayable {
public void print() {
System.out.println("Printing : www.lawtantra.org");

}

public void display() {
System.out.println("Displaying: blog.lawtantra.org");
}
}

public class InterfaceExample {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.print(); // Calling the print() method
obj.display(); // Calling the display() method
}
}


In this program, we define two interfaces, "Printable" and "Displayable". Each interface declares a single abstract method without any implementation details.
Next, we create a class named "MyClass" that implements both interfaces, "Printable" and "Displayable". To implement an interface, we use the "implements" keyword followed by the interface names. The class must provide concrete implementations for all the abstract methods defined in the interfaces.

In 'MyClass', we override the "print()" method from the "Printable" interface and the "display()" method from the "Displayable" interface. We provide the desired implementation within these methods.

In the "main()" method, we create an object of "MyClass" and call the "print()" and "display()" methods. These methods execute the implementation provided in the "MyClass" class.

When you run this program, it will output:

Printing : www.lawtantra.org 
Displaying: blog.lawtantra.org

This demonstrates how a class can implement multiple interfaces in Java and provide the required method implementations. The class "MyClass" successfully implements both "Printable" and "Displayable" interfaces and provides the respective behavior defined by those interfaces.

Post a Comment

0 Comments