CodeGym /Courses /Java Core /How to use abstract classes

How to use abstract classes

Java Core
Level 3 , Lesson 3
Available

"Hello, Amigo! Yesterday you were schooled in the ways of abstract classes. Now it's time to deepen our knowledge. I want to teach you how to use abstract classes correctly."

It's difficult to come up with a real-world analogy for an abstract class. A class is usually a model of some entity. But an abstract class contains methods that have not been implemented, and can contain methods that have been implemented. What does that mean? What analogy for an abstract class can we find? Is there such a thing in the real world?

Actually, there is. Imagine the chassis of an almost finished car on a conveyor belt. I can install either a souped-up engine or a highly efficient engine. Either a leather interior or fabric upholstery. The car's specific implementation is not yet determined. What's more, the chassis could be used to produce several specific implementations. But nobody wants the car in its current form. This is a classic abstract class: creating instances of it wouldn't make sense, so you can't create them; the class only makes sense because of the many full-fledged heirs that will be created on its basis.

"That's easy enough."

But there can be even more abstract analogies. More like interfaces with a few implemented methods. For example, consider a professional interpreter. Without specifying the source and target languages, we have an «abstract translator». Or consider a bodyguard. We may know that he's mastered martial arts and can protect his client. But which martial arts and how he will protect the client are "implementation details" of each specific bodyguard.

Let's look at an example:

Java code Description
abstract class BodyGuard
{
 abstract void applyMartialArts(Attacker attacker);

 void shoot(Attacker attacker)
 {
    gun.shoot(attacker);
 }

 void saveClientLife(Attacker attacker)
 {
  if (attacker.hasGun())
     shoot(attacker);
  else
     applyMartialArts(attacker);
 }
}
The BodyGuard class determines how to deal with an attack: shoot or use martial arts.

However, the specific martial art is not specified, though we are certain that the skill exists.

We can create several different bodyguards (by inheriting this class). All of them will be able to protect the client and shoot the attacker.

3
Task
Java Core, level 3, lesson 3
Locked
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. Turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

"You're right. It's a lot like an interface with a few implemented methods."

"Yes, this type of abstract class is common among standard Java SE classes."

Comments (12)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
ayhem bouabid Level 25, Tunis, Tunisia
11 January 2021
Those creative classes make me want to write my own cool classes as well.
Johannes Level 27, Centurion, Pretoria, South-Africa
21 March 2020
once again: It makes NO sense ?? Why would I complicate anything so much ? "Bodyguard" class can be created non-abstract, and the method "applyMartialArts()" can also be non-abstract, and it will still work in exactly the same manner ?!
Corina Bodea Level 14, Cluj Napoca, Romania
16 April 2020
Hello Hope you already clarified this, but if not, hope it will be useful for you or future codegym fellows. You're not alone in this. :) Actually Amigo had the same problem about complicating our lives with abstraction here: https://codegym.cc/quests/lectures/questcore.level02.lecture05 :D And Kim's answer was: "The advantage of this feature is evident in large projects. The more classes you have, the more clearly you need to delineate their roles. You'll see the advantage of doing this, and soon. Everybody has to go through this." I also loved this idea from one of the previous lectures: "OOP is principles. Programming laws. Each of them restricts us in some way, but in return provides huge advantages as programs grow large. The four principles of OOP are like the four legs of a chair. If you take even one of them away, the entire system becomes unstable." So the main idea of using these principles, including abstraction is for the benefit of the program as it grows larger and for now we don't have such "grandiose" projects. More restrictions and structure, more freedom and stableness. :D I reminded these parts in order for you to get relaxed, enjoy learning these OOP principles and not rushing things up because as you continue to study and practice it will become clearer and clearer.
Johannes Level 27, Centurion, Pretoria, South-Africa
16 April 2020
Thank you Corina! I believe that is the case: we'll only understand some of the weird concepts when it's really needed, i.e. larger programs. Thanks for the type ;)!
Corina Bodea Level 14, Cluj Napoca, Romania
16 April 2020
Answering to second question about this specific example. It works but it's not exactly the same concept. Bodyguard class cannot be instantiated anymore. You cannot access it directly only through inheritance. I guess the main purpose of inheriting an abstract class is getting advantage of what's already implemented in the class, calling the methods, and also having the freedom of implementing your own version for the defined abstract method.

public static class BodyGuard1 extends BodyGuard {
        @Override
        void applyMartialArts(Attacker attacker) {
            // traditional martial arts
        }
        public static void main(String[] args) {
            BodyGuard1 bodyGuard1 = new BodyGuard1();
            Attacker attacker = new Attacker();
            bodyGuard1.saveClientLife(attacker);       //bodyGuard1 only needs to know that he can call this method and have access to it
            bodyGuard1.applyMartialArts(attacker);
        }
    }
Bodyguard1 doesn't need to know HOW saveClientLife or shoot methods are implemented, JUST use them. Through abstraction we are hiding some details. Also applyMartialArts method MUST be implemented in the Bodyguard1 class which inherits the abstract class. It's like Bodyguard abstract class is telling us "Yeah! I know that bodyguards will apply some sort of martial arts but I don't know exactly how or what type, so i will let them to decide, but it's mandatory. Also I know exactly that each bodyguard is using a gun so they will definitely shoot and all bodyguards are working for saving clients life in case of an attacker." I guess a good example would be us on this platform. :D We are definitely taking advantage of it, but we don't need to know how everything it's made behind the scene. And the abstract methods would be the tasks, each one of us is implementing a different solution. What do you think? Hehe. :) Cheers
Corina Bodea Level 14, Cluj Napoca, Romania
17 April 2020
I understand. I am so happy you wrote this Johannes. I am thankful for your sincerity. I will take into account all what you wrote and I will get back.
Corina Bodea Level 14, Cluj Napoca, Romania
17 April 2020
But until then. Focus on quality, not quantity!
Johannes Level 27, Centurion, Pretoria, South-Africa
17 April 2020
Thanks, will do ;) I am going to delete my long replies, so as to not confuse other students etc, have a nice day and thanks for the chat!
Andrei Level 41
26 November 2020
Now I am curious what Johannes deleted, lol! Thank you for the explanations, Corina!
Thomas Level 13, Scottsdale, United States
12 August 2024
Very helpful ! superb @Corina Bodea
10 January 2020
Code entry task in this lesson has very strange intendation, I spent 1 minute writing actual code and 5 minutes correcting intendation...
Isaiah Burkes Level 16, Tampa, United States
23 December 2019
Recognizing the similarities between interfaces and abstract classes has finally cleared this up for me.