InterviewSolution
| 1. |
Abstract class and Interfaces |
||||||||||||
|
Answer» Abstract Class:- In C++, a class becomes abstract if it has at least one pure virtual function. In Java, unlike C++, an abstract class is created using a separate keyword abstract. The following are some key points to remember about Java abstract classes.
Example - abstract class Sample1 {abstract void fun(); } class Sample2 extends Sample2 { void fun() { System.out.println("Inside Sample2's fun function."); } } class Test { public static void main(String args[]) { Base b = new Derived(); // We can have references of Base type. b.fun(); } } Output - Inside Sample2's fun function.Explanation - In the above code, we have defined an abstract class Sample1. We declare the function definition in this class. We define another class Sample2 and extend it from Sample1. Here, we provide the implementation for the method of the abstract class inherited. Now we create an instance of the Sample2 class and invoke the fun() function. Java Interfaces:-
Syntax - interface INTERFACE_NAME {// constant fields // methods } The interface keyword is used to declare an interface. Its purpose is to provide complete abstraction. All methods in an interface are declared with an empty body and are public by default, and all fields are public, static, and final. A class that implements an interface is required to implement all of the interface's functions. The keyword implements is used to implement an interface. Reasons for introducing interfaces in Java:
Example - interface Sample{ final int a = 1; // public, static and final void display(); // public and abstract } // A class that implements the interface. class Test implements Sample { // Implementing the capabilities of the interface. public void display() { System.out.println("InterviewBit"); } public static void main (String[] args) { Test t = new Test(); t.display(); System.out.println(a); } } Output - InterviewBit1 Explanation - In the above code, we created an interface Sample having a public, static and final data member ‘a’ and a function signature with name ‘display’. We create a class Test that implements this interface and provides the definition for the display function. We also access the data member ‘a’ defined in the interface. Abstract Class vs Interface: The following table depicts the differences between abstract classes and interfaces in Java:
|
|||||||||||||