abstract Keyword in Java


An abstract class cannot be instantiated and may contain abstract and non-abstract methods. Abstract classes are used to provide a base for subclasses to extend and implement the abstract methods.

Source Code

abstract class Animal {
    abstract void makeSound(); // Abstract method does not have a body

    void sleep() {
        System.out.println("Zzz");
    }
}

class Pig extends Animal {
    void makeSound() {
        System.out.println("The pig says: wee wee");
    }
}

public class TestAbstract {
    public static void main(String[] args) {
        Pig myPig = new Pig();
        myPig.makeSound();
        myPig.sleep();
    }
}

Use abstract classes when you want to share code among several closely related classes but prevent instantiation of the abstract class.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments