Prashnikaप्रश्निका
Code
About
‹ Back to the paper

Question 2(a)

2 marks

Computer ScienceISC 2019 Computer Science Paper 1Short answerInheritance, Interfaces and Polymorphism

Answer the following in short.

What is an Interface? How is it different from a class?

Answer

Answer

An interface in Java is a reference type that contains only abstract methods (method signatures with no body/implementation) and constants (implicitly public, static and final fields). It defines a contract that any class implementing it must fulfil by providing the actual code for every one of its methods. It is declared with the keyword 'interface' and a class uses it via the keyword 'implements'. Difference from a class: A class defines both the data (instance variables) and the actual implementation (method bodies) of its behaviour, and objects can be created directly from it using 'new'. An interface has no instance variables and no method bodies (only method headers) and cannot be instantiated on its own - it must be implemented by a class. Also, a class can extend only one superclass (single inheritance), whereas a class can implement any number of interfaces, so interfaces are used to achieve a form of multiple inheritance in Java.