Abstract Class Interview Questions in Java

  1) Abstract class must have only abstract methods. True or false?

No, Abstract class can have both abstract method and concreate method.

2) Is it compulsory for a class which is declared as abstract to have at least one abstract method?

No, Abstract class may or may not have abstract method.

It is just we can't create object of Abstract class.

4) Why final and abstract can not be used at a time?

If we make class or method final then we can't modify class and method but Abstract means something which is not complete and it needs modification further. Abstract class or method is modified in the subclass.

5) Can we instantiate a class which does not have even a single abstract methods but declared as abstract?

No, we can't instantiate Abstract class.

6) Can we declare abstract methods as private? Justify your answer?

No. Abstract methods can not be private. Abstract method must be overridden in subclass and if we declare abstract method as private then it can't be overridden.

7) Can we declare abstract method as static?

No we can't declare abstract method as static because static method can't be overridden and abstract method must be overridden.

8) Can abstract method declaration include throws clause?

Yes. Abstract methods can be declared with throws clause.

9) Can abstract class have constructors in Java?

Yes abstract class can have constructor in Java. Since we can't create instances of abstract class but abstract class constructors are used to initialize abstract class instance variables in subclass constructor. Also JVM create default constructor if we don't define any constructor. Let's understand need of abstract class constructor through examples.

  1. abstract class Parent {
  2. int a,b;
  3. public Parent(int a, int b){
  4. this.a=a;
  5. this.b=b;
  6. }
  7. }
  8. public class Child extends Parent {
  9. int a,b,c;
  10. public Child(int a, int b, int c){
  11. super(a,b);
  12. this.c=c;
  13. System.out.println("Value of a is "+a);
  14. System.out.println("Value of b is "+b);
  15. System.out.println("Value of c is "+c);
  16. }
  17. public static void main(String [] args){
  18. Child c = new Child(1,2,3);
  19. }
  20. }
  21.  
10) Can abstract class contains main method in Java?
Yes abstract class can contains main method in Java. It'll be used to execute abstract class until you don't create instance of abstract class.

0 comments:

Post a Comment