#
Abstraction in Java
In Java OPP (Object-Oriented Programming) we speak about 4 main concepts:
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
Abstraction in general hides the implementation details from the user. We can see WHAT an object can do, but not HOW.
Abstraction in Java is realized by using abstract classes and interfaces.
#
Abstract classes
An abstract class is a class which:
- cannot be instantiated
- function as a base for other subclasses
info
In Java an abstract
class is marked using abstract keyword.
Here we have an example of abstract class
in Java:
public abstract class Car {
public void startCar(){
System.out.println("Now we start a car");
};
abstract void buildCar();
}
This class is never instantiated, but can be used to create other classes.
For instance, we can create a VolvoCar class as below:
public class VolvoCar extends Car {
@Override
void buildCar() {
System.out.println("Implement buildCar for VolvoCar.");
}
}
This new class could be instantiated.
You can see a full example of an abstract class usage here.
#
Interfaces in Java
An interface
class in Java is a class which:
- define a collection of
public
andabstract
methods (which will be implemented later) - could define a collection of
public
,static
&final
variables - (starting from Java 8) could define a
default
method and somestatic
methods
Info
As we can see starting from Java 8, the interfaces could contain implementation for some methods (static
or default
).
You can see a full example of an interface usage here.
Note:
- a class could extend a class
- a class could implement an interface