Abstract Class in Java

Abstract Class in Java

2 min read
  • An abstract class is created using an abstract keyword.
  • An abstract class can’t create an object of itself.
  • An abstract class can contain any type of methods such as public, protected, abstract, etc.
  • An abstract class does not have a body of itself.
  • An abstract class can contain ‘n’ number of abstract methods. It can also have static and final variables.
  • When a class extends an abstract class then there is mandatory to provide the definition of all abstract method of an abstract class.
  • An abstract class can contain non-parametrised and parameterized constructor except the default constructor.We can not create an instance of abstract class but we can call it by using instance of base class.

Why not to use default constructor instead of abstract class???

Default constructor is used for creating a new instance(object) using new keyword but an abstract class can’t be instantiated.

An abstract can inherit another abstract class by using multilevel inheritance.

Example:-

import java.util.Scanner;
 abstract class example        //example is the class name
 {
 static int a;
 final int n=5;
 abstract void S_Details();
 }
 class xyz extends example
 {
      String[] name,branch;
      int i;
      name=new String[n];
       branch=new String[n];
       void S_Details()
            {
           for(i=1;i<=n;i++)
             {
              a++;
              System.out.println("Enter the name and branch of Student "+a);
              Scanner sc=new Scanner(System.in);
              name[i]=sc.next();
              branch[i]=sc.next();
 } 
}

 void print()
       {
          System.out.println("Details are ");
          for(i=1;i<=n;i++)
            {
            System.out.println(name[i]+"       "+branch[i]);
           }
      }
 public static void main(String[] args)
 {
         xyz obj=new xyz();
         obj.S_Details();
         obj.print();
 }
 }

Output

Tags:
Choose your Reaction!
Leave a Comment