Java Abstract Class What Is It Good For
Java Abstract Class What Is It Good For
— T O QUIT OR NOT T O QUIT ? — T OP 50 S T ORIES WRIT ERS HERE ARE YOU CURIOUS ?
You have 2 free stories left this month. Sign up and get an extra one for free.
The Java abstract class eludes many Java developers. Let’s learn what it
does for us and how to use it.
Compare
Like interfaces, abstract classes cannot be instantiated. Where the
interface just will contain method signatures an abstract class can
contain a method body. Abstract classes can declare fields that are not
static and final.
Where interfaces have all fields automatically become public, static, and
final. We can implement as many interfaces as we want. Abstract classes
are like regular classes and we can only extend one.
The Java tutorial has some good guidance when to use abstract classes.
When we “want to share code among several closely related classes” or Top highlight
“expect that classes that extend your abstract class have many common
methods or fields”. Interfaces should be used when “expect that
unrelated classes would implement your interface” or “want to specify
the behavior of a particular data type”.
1 package com.myitcareercoach;
2
3 public abstract class Battery {
4 int volt;
5 int amps;
6 void charge(int chargingTime) {
7 // shared code
8 }
9
10 abstract boolean fullyCharged();
11
12 abstract boolean isTooHot();
13
14 }
This Battery abstract class has one implemented method and two
abstract methods. There are also two fields defined as well.
1 package com.myitcareercoach;
2
3 public class ComputerBattery extends Battery {
4
5 @Override
6 boolean fullyCharged() {
7 // TODO Add some code here!
8 return false;
9 }
10
11 @Override
12 boolean isTooHot() {
13 // TODO Add some code here!
14 return false;
15 }
16
17 }
Main?
Would you think if you had the main method in an abstract class that it
would run?
I didn’t think it would either but in fact, it does run. I suggest you try it out
for yourself. As you can see abstract classes have their place in Java.
Similar to interfaces but used in a different way.
A newsletter that delivers The Startup's most popular stories to your inbox once a
month. Take a look
By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more
information about our privacy practices.
WRIT T EN BY
How Convenient A Simple Introduction How to not get caught Side projects: API
Graeco-Latin Squares to Git. while web scraping? Authentication
Are Rajat M in T he Startup Efe Can Kursun in Data Driven Overview
Juan Manuel Dato Investor ACGo in T he Startup
How to debug layout What Makes a Great A Beginner’s Guide to Components and
issues with the Flutter Developer? GraphQL Composition with
Inspector Dhananjay Trivedi in Better Leonardo Maldonado in MVVM + Data Binding
Katie Lee in Flutter Programming freeCodeCamp.org Chris Michael in Kin + Carta
Created