Java Abstract Class

Category: Java   Tags: Java, Java Basic, Java Abstract Class

An abstract class is a class that is declared abstract, it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. Here is the syntax of an abstract class:

                          abstract type ClassName {}
                        

Any class that contains one or more abstract methods must also be declared abstract. A class that extends a abstract class should either implement all method or declare itself a abstract class.

AbstractClassExample.java

                          package com.tutorial.javabasic;

                          abstract class A {
                              abstract void test();

                              void a() {
                                  System.out.println("non abstract method in abstract class");
                              }
                          }

                          class B extends A {

                              @Override
                              void test() {
                                  System.out.println("B's version of test()");
                              }
                          }

                          abstract class C extends A {
                              void c() {
                                  System.out.println("a method in C");
                              }
                          }

                          public class AbstractClassExample {

                              public static void main(String s[]) {
                                  B b = new B();
                                  b.test();
                                  b.a();
                              }
                          }
                        

Output:

                          B's version of test()
                          non abstract method in abstract class
                        

Class A is an abstract class that contains both abstract and non abstract method. Here a() is non abstract method and test() is an abstract method. As you can see an abstract method doesn't have method body and it is declared with abstract keyword.

Class B extend class A and it should implement all abstract method declared in class A. All abstract class is labeled with @Override annotation to indicate that this is a override method.

Class C is declared abstract therefore it doesn't need to implement any abstract method of its parent class.