USING ABSTRACT CLASS

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

Example abstract class

  1. abstract class A{}  

Example 1: abstract method in abstract class

Note: 1) Abstract class can also have regular(or concrete) methods along with abstract methods.
2) Abstract methods do not have body, they just have prototype(method signature).
3) Abstract methods must be implemented in the child class (if the class is not abstract) otherwise program will throw compilation error.
package beginnersbook.com;
//abstract class
abstract class Sum{
   //abstract methods
   public abstract int SumOfTwo(int n1, int n2);
   public abstract int SumOfThree(int n1, int n2, int n3);
   //Regular method 
   public void disp(){
      System.out.println("Method of class Sum");
   }
}

class AbstractDemo extends Sum{
   public int SumOfTwo(int num1, int num2){
 return num1+num2;
   }
   public int SumOfThree(int num1, int num2, int num3){
 return num1+num2+num3;
   }
   public static void main(String args[]){
      AbstractDemo obj = new AbstractDemo();
      System.out.println(obj.SumOfTwo(3, 7));
      System.out.println(obj.SumOfThree(4, 3, 19));
      obj.disp();
   }
}
Output:
10
26
Method of class Sum


abstract method

A method that is declared as abstract and does not have implementation is known as abstract method.

Example abstract method

  1. abstract void printStatus();//no body and abstract  

Example 2: abstract method in interface
All the methods of an interface are public abstract by default.
package beginnersbook.com;
//Interface
interface Multiply{
   //abstract methods
   public abstract int multiplyTwo(int n1, int n2);
   /* We need not to mention public and abstract
    * as all the methods in interface are 
    * public and abstract by default
    */
   int multiplyThree(int n1, int n2, int n3);

   /*Regular (or concrete) methods are not allowed 
    * in an interface. 
    */
}

class AbstractDemo2 implements Multiply{
   public int multiplyTwo(int num1, int num2){
      return num1*num2;
   }
   public int multiplyThree(int num1, int num2, int num3){
      return num1*num2*num3;
   }
   public static void main(String args[]){
      AbstractDemo2 obj = new AbstractDemo2();
      System.out.println(obj.multiplyTwo(3, 7));
      System.out.println(obj.multiplyThree(1, 9, 0));
   }
}
Output:
21
0

No comments:

Post a Comment