Saturday, July 11, 2015

Explain "abstract" keyword

abstract is a keyword in java which is used as a modifier for methods and classes. Abstract methods do not have body(implementation). e.g. abstract void m1();

If a method does not have body, it must be declared to be abstract. If a method is abstract, the class must also be abstract. However abstract classes are classes for which objects cannot be created. If class is abstract, it is not necessary that method(s) should be abstract. A class having no abstract methods may also be declared to be abstract meaning that objects cannot be created for it.
eg.

abstract class A{
        abstract void m1();
        void m2(){

}
}
-          Here since m1 is abstract method, class also must be abstract.
abstract class A{
        void m1(){

}
}
-          Here, even though m1 is not abstract, class can be abstract - meaning objects cannot be created of class A

abstract class A{
        abstract void m1();
}
class B extends A{
        void m1(){

        }
}
- Here, since class A is having a abstract method, class B must override/implement the method. Otherwise, B will inherit that abstract method from A, and B also needs to be an Abstract Class then.


- Abstract classes can have constructors
(But objects cannot be created. Then what's the use of constructor? )
Abstract classes have constructors which cannot be directly invoked to create objects but are invoked by subclasses using super()

1 comment:

  1. can you add theory for Dynamic Method Dispatch and also little explanation about the object class in java.

    ReplyDelete