JavaRush /Java Blog /Random EN /Abstract classes in Java with specific examples

Abstract classes in Java with specific examples

Published in the Random EN group
Hello! In previous lectures, we got acquainted with interfaces and figured out what they are needed for. Today's topic will have something in common with the previous one. Let's talk about abstract classes in Java. Abstract classes in Java with concrete examples - 1

Why are classes called "abstract"

You probably remember what “abstraction” is - we’ve already covered it :) If you suddenly forgot, it’s okay, let’s remember: this is the principle of OOP , according to which when designing classes and creating objects, it is necessary to highlight only the main properties of an entity and discard the secondary ones. For example, if we are designing a class SchoolTeacher- a school teacher - we are unlikely to need the “ height ” characteristic. Indeed: for a teacher this characteristic is not important. But if we create a class in the program BasketballPlayer- a basketball player - height will become one of the main characteristics. So, an abstract class is the most abstract, oh-so-approximate “blank” for a group of future classes. This preparation cannot be used in its finished form - it is too “raw”. But it describes a certain general state and behavior that future classes - inheritors of the abstract class - will have.

Java Abstract Class Examples

Let's look at a simple example with cars:
public abstract class Car {

   private String model;
   private String color;
   private int maxSpeed;

   public abstract void gas();

   public abstract void brake();

   public String getModel() {
       return model;
   }

   public void setModel(String model) {
       this.model = model;
   }

   public String getColor() {
       return color;
   }

   public void setColor(String color) {
       this.color = color;
   }

   public int getMaxSpeed() {
       return maxSpeed;
   }

   public void setMaxSpeed(int maxSpeed) {
       this.maxSpeed = maxSpeed;
   }
}
This is what the simplest abstract class looks like. As you can see, nothing special :) What might we need it for? First of all, he describes the entity we need as abstractly as possible - a car. The word abstract is here for a reason. There are no “just machines” in the world. There are trucks, race cars, sedans, coupes, SUVs. Our abstract class is simply a “blueprint” from which we will later create car classes.
public class Sedan extends Car {

   @Override
   public void gas() {
       System.out.println("The sedan accelerates!");
   }

   @Override
   public void brake() {
       System.out.println("The sedan slows down!");
   }

}
This is a lot like what we talked about in the lectures about inheritance. Only there we had a class Carand its methods that were not abstract. But this solution has a number of disadvantages, which are corrected in abstract classes. First and foremost, an instance of an abstract class cannot be created:
public class Main {

   public static void main(String[] args) {

       Car car = new Car(); // Error! The Car class is abstract!
   }
}
This “trick” was implemented specifically by the creators of Java. Once again, just to remember: an abstract class is just a blueprint for future "normal" classes . You don't need copies of the drawing, right? So there is no need to create instances of an abstract class :) And if the class Carwere not abstract, we could easily create its objects:
public class Car {

   private String model;
   private String color;
   private int maxSpeed;

   public void gas() {
       // some logic
   }

   public  void brake() {
       // some logic
   }
}


public class Main {

   public static void main(String[] args) {

       Car car = new Car(); // Everything is OK, the machine has been created
   }
}
Now we have some kind of strange car in our program - not a truck, not a racing car, not a sedan, but something in general. That same “just a machine” that does not exist in nature. The same example can be given with animals. Imagine if objects appeared in your program Animal- “ just an animal ”. What type it is, what family it belongs to, what characteristics it has - it is not clear. It would be strange to see him on the program. There are no “just animals” in nature. Only dogs, cats, foxes, moles and others. Abstract classes free us from “ just objects ”. They give us a basic state and behavior. For example, all cars must have a model , color and maximum speed , and they must also be able to gas and brake . That's all. This is a general abstract scheme, then you yourself design the classes you need. Please note: two methods in an abstract class are also designated as abstract , and they are not implemented at all. The reason is the same: abstract classes do not create "default behavior" for "mere machines". They just say they should be able to make all the cars. However, if you still need the default behavior, you can implement methods in an abstract class. Java does not prohibit this:
public abstract class Car {

   private String model;
   private String color;
   private int maxSpeed;

   public void gas() {
       System.out.println("Let's go!");
   }

   public abstract void brake();

   //getters and setters
}


public class Sedan extends Car {

   @Override
   public void brake() {
       System.out.println("The sedan slows down!");
   }

}

public class Main {

   public static void main(String[] args) {

       Sedan sedan = new Sedan();
       sedan.gas();
   }
}
Console output: “Get accelerating!” As you can see, we implemented one method in the abstract class, but did not implement the second. As a result, the behavior of our class Sedanwas divided into two parts: if you call a method on it gas(), it will “pull up” from the parent abstract class Car, and brake()we redefined the method in the class Sedan. It turned out to be very convenient and flexible. But now our class is not so abstract ? After all, in fact, half of his methods are implemented. In fact - and this is a very important feature - a class is abstract if at least one of its methods is abstract . At least one of two, at least one of a thousand methods - it doesn’t matter. We can even implement all the methods and not leave any abstract ones. There will be an abstract class without abstract methods. In principle, this is possible, and the compiler will not produce errors, but it is better not to do this: the word abstract will lose its meaning, and your fellow programmers will be very surprised to see this :/ Moreover, if a method is marked with the word abstract, each descendant class must implement or be declared abstract. Otherwise the compiler will throw an error . Of course, each class can inherit from only one abstract class, so in terms of inheritance there is no difference between abstract and regular classes. It doesn’t matter whether we inherit from an abstract class or from a regular one, there can only be one parent class.

Why is there no multiple class inheritance in Java?

We have already said that there is no multiple inheritance in Java, but we haven’t really figured out why. Let's try this now. The point is that if Java had multiple inheritance, child classes would not be able to decide which behavior to choose. Let's say we have two classes - Tosterand NuclearBomb:
public class Toster {


 public void on() {

       System.out.println("The toaster is on, the toast is getting ready!");
   }

   public void off() {

       System.out.println("The toaster is off!");
   }
}


public class NuclearBomb {

   public void on() {

       System.out.println("Взрыв!");
   }
}
As you can see, both have a method on(). In the case of a toaster, it starts cooking toast, and in the case of a nuclear bomb, it causes an explosion. Oh :/ Now imagine that you decided (I don’t know why suddenly!) to create something in between. And here it is your class - MysteriousDevice! This code, of course, does not work, and we present it simply as an example of “how it could be”:
public class MysteriousDevice extends Toster, NuclearBomb {

   public static void main(String[] args) {

       MysteriousDevice mysteriousDevice = new MysteriousDevice();
       mysteriousDevice.on(); // And what should happen here? Will we get a toast, or a nuclear apocalypse?
   }
}
Let's see what we got. The mysterious device comes from both the Toaster and the Nuclear Bomb. Both have a method on(), and as a result, it is not clear which method on()should fire on the object MysteriousDeviceif we call it. The object will not be able to understand this. Well, as a cherry on the cake: the Nuclear Bomb has no method off(), so if we guessed wrong, there will be no way to turn off the device. Abstract classes in Java with concrete examples - 2 It is precisely because of this confusion, when an object is not clear which behavior it should choose, that the creators of Java abandoned multiple inheritance. However, you remember that Java classes implement many interfaces. By the way, you have already encountered at least one abstract class in your studies! Although, maybe I didn’t notice it :)
public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar>
This is your old friend - class Calendar. It is abstract and has several heirs. One of them is GregorianCalendar. You already used it in lessons about dates :) Everything seems to be clear, there is only one point left: what is the fundamental difference between abstract classes and interfaces ? Why did they add both to Java, and not limit themselves to just one? This could well be enough. We'll talk about this in the next lecture! See you:)
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION