Abstract Classes Examples in Java Week 9 Session 2
Abstract Classes Examples in Java Week 9 Session 2
classes and
methods with
examples
Outline
Recap
Abstract classes and methods with Examples
Overriding of Abstract Methods
Accesses constructor of Abstract Classes
why we can not instantiate abstract class
Uses and purpose
References
Recap
Abstract classes, why we use
Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only
essential information to the user.
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
A method without a body is known as an Abstract Method. The body is provided by the
subclass (inherited from).
The abstract method will never be final because the abstract class must implement all the
abstract methods.
From this example, it is not possible to create an object of the Animal class:
Remember from the Inheritance lecture that we use the extends keyword
to inherit from a class.
Overriding of Abstract Methods
class Dog extends Animal { Here, we have used the super() inside the
Dog() constructor of Dog to access the
{ constructor of the Animal.
super();
... Note that the super should always be the
} first statement of the subclass constructor.
}
Another example
abstract class Animal
{
abstract void makeSound();
} class Main
class Dog extends Animal {
{ public static void main(String[] args)
public void makeSound() {
{ Dog d1 = new Dog();
System.out.println("Bark bark."); d1.makeSound();
}
} Cat c1 = new Cat();
class Cat extends Animal c1.makeSound();
{ }
public void makeSound() }
{
System.out.println("Meows ");
}
}
why we can not instantiate abstract class
To achieve security - hide certain details and only show the important details of an object.
The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class
from which other classes can inherit. Abstract classes cannot be used to instantiate objects and
serves only as an interface. Attempting to instantiate an object of an abstract class causes a
compilation error.
THANK YOU