Q: What is the difference between Abstract class and interface?
Ans:
Ans:
Abstract
Class
|
Interface
|
| 1) Abstract class can have abstract and non- abstract methods. | 1) Interface can have only abstract methods. |
| 2) It doesn't support Multiple Inheritance. | 2) Interface Supports Multiple Inheritance |
| 3) Abstract keyword is used to declare Abstract class | 3) interface keyword is used to declare an interface. |
| 4) Abstract class can contain static,non-static, final, non-final variables. | 4) by default Interface variables are only static & final. |
| 5) Abstract class can have static methods, main method. | 5) Interface can't contain static method , main method. |
| 6) Abstract class can contains Constructors | 6) Interface can't contain Constructors. |
| 7) Abstract class methods can be declared with public and non-public | 7) By default all interface methods are public & abstract. |
| 8) A abstract class can provide implement of interface. | 8) A interface can't provide implementation of abstract class. |
| 9) A abstract class can extends only one class. | 9) A interface can extends any number of interfaces. |
| 10) Object class is super class to all classes. | 10) There is no super class for interface. |
| Ex:
public abstract class B { public abtract void fun1(); void fun2(); } public class A extends B { public void fun1() { System.out.println("fun1 of class A is calling"); }
public void fun2()
{System.out.println("fun2 of class A is calling"); } public static void main(String[] a) { A a1=new A(); a1.fun1(); a1.fun2(); } } O/P: fun1 of class A is calling fun2 of class A is calling |
Ex:
interface B { int x=10; void fun1(); } public class A implements B { public void fun1() { System.out.println("fun1 of class A is calling"); } public static void main(String[] a) { A a1=new A(); a1.fun1(); } } O/P: fun1 of class A is calling |
No comments:
Post a Comment