Have a Question?

If you have any question you can ask below or enter what you are looking for!

What is the use of Abstract modifier in Java

Abstract class vs Abstract method

  • If a class contain at least one abstract method then compulsory we should declare the class as abstract otherwise we will get compile time error.

â–¡ Reason If a class contain at least one abstract method then the implementation is not complete and hence it is not recommended to create an object to restrict object instantiation compulsory we should declare the class as abstract.

  • Even though the class doesn’t contain any abstract method still we can declare the class as abstract if we don’t want instantiation i.e. abstract can contain zero number of the abstract method also.
  • If we are extending Abstract class then for each and every abstract method of parent class we should provide implementation, otherwise, we have to declare child class as abstract. In this case, next level child class is responsible to provide the implementation.

Example..What is the use of Abstract modifier in Java
package com.java4us;
abstract class Parent {
    public abstract void m1();

    public abstract void m2();
}

class Child extends Parent {
    public void m1() {
    }
}
// CE:-Child is not abstract and does not override abstract method m2() in Parent.

 

Final vs Abstract

  • Abstract method compulsory we should override in child classes to provide implementation whereas we can’t override final method hence Final-Abstract combination is an illegal combination for methods.
  • For final classes, we can’t create child class whereas for abstract classes we should create the child class to provide an implementation. Hence final-Abstract combination is illegal for classes.
  • An abstract class can contain final method whereas final class can’t contain an abstract method
  • Its is highly recommended to use abstract modifier because it promotes several OOPS features like inheritance and polymorphism.

Tags:  , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published.