IGNOU MCS-024 Object Oriented Technology and Java Programming , Latest Solved Assignment (July 2023 - January 2024 )
Q2. What is meant by interface in Java? Explain its use with an example.
Ans. In Java, an interface is a reference type that defines a contract of methods that a class implementing the interface must provide. It’s a way to achieve abstraction and define a set of methods that any implementing class must adhere to. Interfaces allow multiple classes to share common methods without necessitating a common base class.
Key points about Java interfaces:
- An interface is declared using the `interface` keyword.
- All methods declared in an interface are implicitly `public` and `abstract`, meaning they have no method body.
- Java classes can implement multiple interfaces.
- A class implementing an interface must provide concrete implementations for all the methods declared in the interface.
Example of using an interface in Java:
// Define an interface named Printable
interface Printable {
void print();
}
// Implement the Printable interface in two classes
class Book implements Printable {
String title;
Book(String title) {
this.title = title;
}
@Override
public void print() {
System.out.println(“Printing book: ” + title);
}
}
class Magazine implements Printable {
String name;
Magazine(String name) {
this.name = name;
@Override
public void print() {
System.out.println(“Printing magazine: ” + name);
}
}
public class Main {
public static void main(String[] args) {
Printable printable1 = new Book(“Introduction to Java”);
Printable printable2 = new Magazine(“Tech Weekly”);
printable1.print(); // Output: Printing book: Introduction to Java
printable2.print(); // Output: Printing magazine: Tech Weekly
}
}
Interfaces are commonly used in Java to achieve polymorphism, allowing different classes to provide their own implementations for a common set of methods defined in the interface. This promotes code reusability and modularity in Java programs.
Assignment Submission Last Date
The IGNOU open learning format requires students to submit study Assignments. Here is the final end date of the submission of this particular assignment according to the university calendar.
30th April (if Enrolled in the June Exams)
31st October (if Enrolled in the December Exams)