Starting Out with Java
From Control Structures through Objects
Lecture No. 24 (Chapter 10:) Abstraction
May 18, 2021
1/9
Abstraction
Data Abstraction: Hiding implementation details and showing
only essential information (e.g. functionality) to the user.
Abstraction achieved with:
Abstract Class
Interface
2/9
Abstract Methods
Abstract Method: A method without body (i.e. no
implementation).
Abstract method must always be declared in an abstract class.
An abstract method has only a header and no body.
AccessSpecifier abstract ReturnType MethodName(ParameterList);
An abstract method is a method that appears in a superclass,
but expects to be overridden in a subclass.
3/9
Abstract Methods
Notice: Keyword abstract appears in the header, and that the
header ends with a semicolon.
public abstract void setValue(int value);
Any class that contains an abstract method is automatically
abstract.
If a subclass fails to override an abstract method, a compiler
error will result.
Abstract methods are used to ensure that a subclass
implements the method.
4/9
Abstract Classes
Abstract Class: A class must declared with an abstract
keyword.
It can have abstract and non-abstract methods (a.k.a.
concrete methods).
An abstract class cannot be instantiated.
It can have constructors, nal methods, and static methods.
Syntax:
public abstract class ClassName{
...
}
5/9
Why we need an Abstract Class
Lets say we have a class Animal that has a method
animalSound () and the subclasses of it like Cow, Cat, Lion
etc.
Since the animal (e.g. cat, lion) sound diers from one animal
to another, there is no point to implement this method in
Animal class.
Thus, making Animal class's animalSound method abstract
would be the good choice as by making this method abstract
we force all the subclasses (e.g. Cat, Lion) to implement this
method with its own implementation details.
6/9
Example: Abstract Class and Methods
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Cow extends Animal {
@Override
public void animalSound() {
System.out.println("The cow says: moo moo");
}
}
class Cat extends Animal {
@Override
public void animalSound() {
System.out.println("The cat says: meow meow");
}
}
Remark: animalSound is an abstract method and it is
implemented by Cat and Cow class.
7/9
Example: Abstract Class
Example is provided in the lecture!
8/9
Credit
Tony Gaddis, Starting out with Java: From Control Structures
through Objects, 6th Edition, Pearson 2016.
9/9