Coders Packet

Abstract Methods using JAVA

By Aryan Pradhan

In this Java tutorial, we will learn about the abstract method and also understand the program.

To first understand abstract methods let us first understand what is abstraction,

Data Abstraction

Data Abstraction refers to the act of hiding the internal details and functionality from the user. It means showing only the essential details to the user rather than showing the whole functionality. 

To understand the concepts of Abstract Methods we also need to understand the concept of an abstract class,

Abstract Class

An abstract class is one that simply represents a concept and whose objects cant be created. It is created through the use of a keyword called abstract.

Syntax:

abstract class class_name{}

Abstract Methods

Abstract methods are methods with no method statements. Subclasses must provide the method statements for the inherited abstract methods. An abstract class is a method without any body. 

Syntax:

abstract return_type method_name( [argument ] );  

Important Points to remember:

1. The abstract method does not have any body, but they have a method declaration. The class which extends the abstract class implements the abstract method.

2. It is not necessary that an abstract method would be present in every abstract class.

3. The abstract method makes the class an abstract method.

4. An abstract method does not have any curly braces but has semi-colons at the end.

 

Now let us understand the abstract method using a sample code:

abstract class car{  
   car(){
       System.out.println("Car is created");}  
   abstract void run();  //abstract method declared
   void changegear(){
       System.out.println("the gear is changed");
    }  
 }  
//Creating a Child class which inherits Abstract class  
 class Maruti extends car{  
 void run(){
     System.out.println("running with safety");}  
 }  
//Creating a Test class which calls abstract and non-abstract methods  
 class TestAbstraction{  
 public static void main(String args[]){  
  car obj = new Maruti();  
  obj.run();  
  obj.changegear();  
 }  
}  

Output:

car is created

running with safety

the gear is changed

Download Complete Code

Comments

No comments yet