Skip to main content

abstract class in java with example

An abstract class is a class, that is declared as abstract. Abstract class contains 0 or more abstract methods. Abstract classes can not be instantiated but that can be sub classed.

          An abstract method is a methods that is declared without any implementation. Like this,

1
2
3
abstract class Car {
   abstract void show();
}

          •  A class with abstract methods is called abstract class. The both abstract method and abstract class must be declared with abstract.
          •  In case where you want to use implementation inheritance then it is usually provided by an abstract base class. Abstract classes are excellent candidates inside of application frameworks.
          •  Abstract classes let you define some default behavior and force sub-classes to provide any specific behavior.
         
          Here is the abstract class example with abstract methods as well as concrete methods.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.javatbrains.abstractclass;

abstract class Car {
     // every car will have a regno;
     int regno;

     // to store regno value
     Car(int no) {
          regno = no;
     }

     /*
      * Every car will have a fuel tank. The mechanism to fill           the tank is same
      * for all cars
      */
     void fillTank() {
          System.out.println("Take the key and fill tank");
     }

     /*
      * Every car will have steering. But different cars will have different
      * steering mechanism
      */
     abstract void steering(int direction);

     /*
      * Every car will have breaks. But different cars will have different
      * breaking mechanism
      */
     abstract void breaking(int force);
}

          Here we will create another concrete class name called Maruti. This class is the sub class of the above abstract class Car.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package com.javatbrains.abstractclass;

class Maruti extends Car {

     Maruti(int no) {
          super(no);
     }

     @Override
     void steering(int direction) {
          System.out.println("Maruti uses manual steering. Please drive the car");
     }

     @Override
     void breaking(int force) {
          System.out
                   .println("Maruthi uses hydraulic breakes. Apply breakes to stop the car");
     }

}

          Here is the another concrete class name called Santro. This is also the sub class of the abstract class Car.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package com.javatbrains.abstractclass;

class Santro extends Car {

     Santro(int no) {
          super(no);
     }

     @Override
     void steering(int direction) {
          System.out.println("Santro uses power steering. Start the car");
     }

     @Override
     void breaking(int force) {
          System.out.println("Santro uses gas breakes. Apply breakes to stop the car");
     }

}

          Now, here we will write a class to all the above classes name called UseCar.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package com.javatbrains.abstractclass;

public class UseCar {

     public static void main(String[] args) {
          // Take new Maruti and Santro cars
          Maruti ma = new Maruti(1234);
          Santro sa = new Santro(007);
          // create a reference to car class
          Car car = ma; // (or) Car car = sa;
          // now use it
          car.fillTank();
          car.steering(10);
          car.breaking(20);
     }

}
OutPut:
     Take the key and fill tank
     Maruti uses manual steering. Please drive the car
     Maruthi uses hydraulic breakes. Apply breakes to stop the car

Key points of Abstract class:
           •  An abstract class is a class with 0 or more abstract methods
           •   An abstract class can have variables, concrete methods and abstract methods.
           •  we cannot create an object to abstract class. But we can create a reference variable to abstract class.
           •   All the abstract methods of the abstract class should be implemented in its sub class.
           •  If an abstract method is not implemented then the sub class should be declared as abstract.
           •   The reference of abstract super class can not refer to the individual methods of the sub class.
           •   The abstract class can not be both abstract and final.
           •   An abstract class must be sub classed.
           •  An abstract class will have constructors, and those constructors are always called when a concrete sub class is instantiated.
         
          If you want to read about the interface with examples. Click Here.

When should you use, abstract class or interfaces?
            •   Consider using abstract classes if any of these statements apply to your situation:
        1. You want to share code among with several closely related classes.
        2. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public.
       3. You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
           •  Consider using interface, if any of these statements apply to your situation:
       1. You expect that unrelated classes would implements your interface. For example, interfaces comparable and cloneable are implements many unrelated classes.
       2. You want to specify the particular behaviour of a data type, but not concerned about who implements its behaviour.
       3. You want to take advantage of multiple inheritance of type.

Comments

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...