+92 332 4229 857 99ProjectIdeas@Gmail.com

Abstract Classes In Java


Are those classes which can’t be instantiated means you can’t create their object. Generally, an abstract class is a class which contains both proper implementations of its public methods or only the prototypes of methods also. And a class which extends this abstract class, now its responsibility to provide the implementations of those methods which are left and if it provides the proper implementations of those methods then we call this class (which extending the abstract class) a concrete class and if it don’t provide then this class have to declare itself an abstract, otherwise if it don’t declare itself an abstract then compiler wont compile it. Whenever there is a "IS-A relationship" use this.


Code




For example:


public abstract class Shape {

       private int area;

       private int circumference;

      

       public Shape() {

              area = 10;

              circumference = 200;

       }

      

       public abstract void compute();//this method has no implementation

      

       public void display(){

             

       System.out.println("Area Is : " + area + "\n" + "Circumference Is : "

                           + circumference);

       }
}


public static void main(String[] args) {

       Shape s = new Shape();//will give you an error, can't instantiate Shape
}

Extending an abstract class:


For example: 


public abstract class Shape {

       private int area;

       private int circumference;

      

       public Shape() {

              area = 10;

              circumference = 200;

       }

      

       public abstract void compute();//this method has no implementation

      

       public void display(){

             

       System.out.println("Area Is : " + area + "\n" + "Circumference Is : "

                           + circumference);

       }
}


public class Circle extends Shape {//will have to give compute method implementation

       public void compute() {//have to give compute() method implementation

              System.out.println("Computing");        

       }

public static void main(String[] args) {

              Circle c = new Circle();

       c.compute();

}

}

If you don’t like to give implementation of abstract method compute implementation then declare Circle class abstract like this:


public abstract class Circle extends Shape {


       public void circleDisplay(){}


public static void main(String[] args) {


}

}

0 comments: