Abstract Class & Method in Java

  • June 3, 2022
  • Java
java thread class

In Java, an abstract class is specified with the abstract keyword. Both abstract and non-abstract methods can be used (method with the body).
Note: Abstraction is the process of hiding implementation details from the user and only displaying functionality.

  • A class that is declared using the abstract keyword is known as an abstract class.
  • Abstract classes are identical to regular classes, except they can also feature abstract methods in addition to concrete methods.
  • We are unable to generate abstract class objects.
  • The code below creates the abstract class MyAbstractClass.
 abstract class MyAbstractClass {
    // Class body
 }  
  • The abstract keyword must be used when declaring an abstract class.
  • There are both abstract and non-abstract methods that can be used.
  • It isn’t possible to instantiate it.
  • This class may also include constructors and static methods.
  • It can have final methods, which prevent the subclass from changing the method’s body.
Abstract Method in Java:

An abstract method is a method that is declared as abstract but does not have any implementation.

An example of an Abstract class that has an abstract method

Bike, in this case, is an abstract class with only one abstract method, run. The Honda class is responsible for its implementation.

abstract class Bike{  
  abstract void run();  
}  
class Honda4 extends Bike{  
void run(){System.out.println("running safely");}  
public static void main(String args[]){  
 Bike obj = new Honda4();  
 obj.run();  
}  
}  
Output:
running safely
Bank example using abstract class & method:
abstract class Bank{    
abstract int getRateOfInterest();    
}    
class SBI extends Bank{    
int getRateOfInterest(){return 8;}    
}    
class PNB extends Bank{    
int getRateOfInterest(){return 6;}    
}    
    
class TestBank{    
public static void main(String args[]){    
Bank b;  
b=new SBI();  
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
b=new PNB();  
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
}}    
Output:
Rate of Interest is: 8 %
Rate of Interest is: 6 %

Note: also read about the Sub packages in Java

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *