Thursday, March 30, 2017

Abstract Modifier in java


Abstract modifier:-

Abstract is he modifier applicable for classes and methods but not for variables.

Abstract method:-

Even though we don’t know about implementation still we can declare a method with abstract modifier i.e for abstract methods only declaration is available but no implementation. Hence abstract method declaration should ends ends with “ ; “ (semicolon).

Ex :-

public abstract void m1();
public abstract void m1(){}
child class is responsible to provide implementation for parent class abstract methods.

Ex:- 

package com.javahighq.java4ever;

public abstract class Vesicle {
abstract public int getNoOfWheels();
}
class Bus extends Vesicle{

      @Override
      public int getNoOfWheels() {
            return 7;
      }
     
}
class Auto extends Vesicle{
      @Override
      public int getNoOfWheels() {
            return 3;
      }
}


By declaring abstract method in the parent class we can provide guidelines to the child classes such that which methods compulsory child has to implements.
Abstract methods never talks about implementation if any modifier takes about implementation then it forks illegal combination with abstract modifier.
The following are various illegal combinations of modifiers for methods with respect to abstract.
These are all illegal combination of abstract modifiers for abstract methods.

Abstract class:-

For any java class if we are not allowed to create an object (because of partial implementation) such type of class we have to declare with abstract modifier
i.e for abstract classes instantiation is not possible.

Ex :-

package com.javahighq;

public abstract class Vesicle {
      public static void main(String[] args) {
            Vesicle vesicle=new Vesicle();
//Cannot instantiate the type Vesicle Test is abstract: Cannot instantiate
      }

}

No comments:

Post a Comment