Java Abstract keyword

The abstract keyword in Java is used to define abstract classes and methods. It plays a key role in achieving abstraction in object-oriented programming, allowing you to define methods without implementation and enforce implementation by subclasses.

Abstract Class:

An abstract class is a class declared with the abstract keyword. It:

  • Can include abstract methods (methods without implementation) and concrete methods (methods with implementation).
  • Cannot be instantiated (you cannot create objects of an abstract class).
  • Serves as a blueprint for subclasses.


Syntax:

abstract class ClassName {
    // Abstract method (no implementation)
    abstract void abstractMethod();


    // Concrete method (with implementation)
    void concreteMethod() {
        System.out.println("This is a concrete method.");
    }
}
Example
abstract class Animal {
// Abstract method
abstract void sound();

// Concrete method
void eat() {
System.out.println("This animal eats food.");
}
}

class Dog extends Animal {
void sound() {
System.out.println("Dog barks.");
}
}

public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Calls the overridden method
myDog.eat(); // Calls the inherited concrete method
}
}

Try it yourself


Abstract Methods:

An abstract method:

  • Is declared using the abstract keyword.
  • Does not have a body (implementation).
  • Must be implemented by any concrete subclass of the abstract class.
Example
abstract class Shape {
abstract void draw(); // Abstract method
}

class Circle extends Shape {
void draw() {
System.out.println("Drawing a Circle.");
}
}

class Rectangle extends Shape {
void draw() {
System.out.println("Drawing a Rectangle.");
}
}

public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle();
shape1.draw();

Shape shape2 = new Rectangle();
shape2.draw();
}
}

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.