Java is learning recently. Stuck on the fact that I can not understand the role of an abstract class in java. In the textbook (not only in one) I found an example describing the role of an abstract class:

// Базовая арифметическая операция abstract class Operation { public abstract int calculate(int a, int b); } // Сложение class Addition { public int calculate(int a, int b) { return a+b; } } // Вычитание class Subtraction { public int calculate(int a, int b) { return ab; } } class Test { public static void main(String s[]) { Operation o1 = new Addition(); Operation o2 = new Subtraction(); o1.calculate(2, 3); o2.calculate(3, 5); } } 

But remaking an ordinary class from an abstract class, and even deleting it altogether, the program did not stop working:

 // Базовая арифметическая операция class Operation { public int calculate(int a, int b) { return a*b; } } // Сложение class Addition extends Operation { public int calculate(int a, int b) { return a+b; } } // Вычитание class Subtraction extends Operation { public int calculate(int a, int b) { return ab; } } class Test { public static void main(String s[]) { Operation/*Addition*/ o1 = new Addition(); Operation/*Subtraction*/ o2 = new Subtraction(); Operation/*Subtraction*/ o3 = new Subtraction(); Operation o4 = new Operation(); System.out.println(o1.calculate(2, 3)); System.out.println(o2.calculate(3, 5)); System.out.println(o3.calculate(10, 20)); System.out.println(o4.calculate(10, 10)); System.out.println(o1.getClass()==o2.getClass()); System.out.println(o3.getClass()==o2.getClass()); } } 

Please describe an example in which the deletion of an abstract class (or "remaking" into a regular one) is impossible and will lead to an error, or just explain in what situations an ordinary class will not replace the abstract one. Thank you in advance.

    5 answers 5

    What kind of textbook, if not a secret? Decent books on Java still provide the basics of OOP.

    The bottom line is this. When you mark a class as abstract , you prohibit it from being instantiated. Since the Operation method is not defined in the Operation class, you should not be able to create instances of it:

     Operation o = new Operation(); 

    If there are no abstract methods in the class, then “redoing” it into the usual one will not manifest itself outwardly. It will just be possible to create an instance of this class.

    Specifically, in your "remake" you defined the body for the calculate method, thereby changing the logic of the work of your entire hierarchy. If you now create another child class from Operation and do not define the calculate method in it, it will use the implementation from the parent class, that is, calculate the product of two arguments.

    and even removing it altogether, the program did not stop working:

    I do not believe. If you deleted the Operation class, you would have to edit the child classes (remove the extends and edit the main ). In addition, after this, your Addition and Subtraction classes would become independent of each other.

    In general, abstract classes are widely used when you need to implement some common functionality for a family of classes.

    • tutorial - MIPT's lecture course on programming in java I actually did (“you would have to edit the child classes (remove extends and edit the main)”). In other words, the abstract class prohibits instantiating itself and generalizing the functionality of similar (child) classes? and another question based on the above written program (mine): what are the advantages of the “truncated” object Operation o3 = new Subtraction (); over "full"? Subtraction o3 = new Subtraction (); - arachnoden
    • one
      The object is not trimmed. This is the use of the principle of polymorphism. We declare the object as belonging to a wider class and assign it a concrete implementation as a child class. This ensures the interchangeability of the child classes: it doesn’t matter to us that it’s slipped, we work uniformly with objects. You would start to deal with the fundamental principles of the PLO. With regard to Java, read Ekkel or something ("Java Philosophy"). - Nofate

    Colleagues, in my opinion of course, do not quite correctly place accents. First of all, an abstract class is, of course, not a class that cannot be created, but a class whose implementation is divorced from its declaration.

    Abstraction in the general sense is detachment from detail. In our case, this is a class declaration without worrying about its implementation. Well, the implementation in each case can be different - sometimes difficult, sometimes simple. And the abstract class has no implementation.

    I will try to give an example from real life:

    1. Suppose we want to describe the ways of assembling and disassembling different furniture, for which we ask the class Мебель
    2. In this case, Мебель typical abstract class with two abstract methods: Собрать and Разобрать . Since the methods of assembling and disassembling furniture depend on a specific model, it is not possible in the Мебель class to describe them, therefore we declare them as abstract.
    3. Next, we set the Стол class, which inherits from the Мебель class, in which we implement the Собрать/Разобрать methods - well, something like: screw the legs, then cross, and so on.
    4. Next, we set the Диван class, which inherits from the Мебель class, in which again we implement the Собрать/Разобрать methods - now: to fasten the back, then the armrests, and so on.

    Further, the most interesting and important begins for the sake of which all this circus with horses is actually started:

    • If there were no abstract classes, the Столы and Диваны would bring the assembly wizard. Well, the type - the master sees that this Стол takes the instructions for assembling it and assembles it. He must know for sure that this is a table or a sofa, otherwise the pipe - the assembly will not take place.
    • In the presence of an abstract class, the master is not brought a Стол or Диван , but simply some Мебель . The master in general, on the drum table is a sofa or a wardrobe. The master pulls out an attached instruction sheet from the furniture and collects it.

    Feels the difference?

    • You rather described interfaces . And the phrase "abstract class has no implementation" is not correct. First, an abstract class can have an implementation that will be common to all its descendants. Secondly, this is the idea of ​​an abstract class: to bring the implementation of the general functionality of some entities into an abstract class, and to designate the unique functionality in abstract methods. - Alex Kisel
    • Lord, another unrecognized guru :) - Barmaley
    • Take an example from more advanced gurus :) And if in the case, in this particular case, despite all your merits, you are misleading your readers. - Alex Kisel
    • Judging by your comments, you have some kind of mess in your head: an abstract class can have an implementation that will be common to all its heirs - even this opus already leads to sad thoughts ... It is certainly true, but this is a common property of any class, and is there an abstract class? In general, I propose not to exacerbate the discussion, you have voted, expressed your opinion, and I’ll end up with my own :) - Barmaley
    • Sorry, but for the sake of truth, let's bring the dispute to the end. My, as you say porridge , is just clear: an abstract class can have an implementation that will become common to its descendants and, in doing so, should in abstract methods designate a functionality that is mandatory for the implementation by the heirs to be unique to them. Your position: "abstract class has no implementation" - is not very clear. If possible, clarify your point. And, please, without arguments ad hominem - unpleasant: ( - Alex Kisel

    For example, we write a system of accounting for aircraft at the airport. There are cargo and passenger airplanes and it is necessary, for example, to have a list of airplanes that are now at the airport. We make an abstract class "airplane" (we do not know in advance which aircraft will arrive) and determine some basic fields suitable for any aircraft (flight speed and length, for example)

     public abstract class Flight { int speed, width; } 

    Next, we create two classes, one for a passenger plane and one for a cargo one, and in each we add specific parameters to it.

     public class PassFlight extends Flight { int maxPassengers; //макс число пассажиров } public class Freighter extends Flight { int maxCargo; //макс грузоподъёмность } 

    Further, already in the class that will work with all this business, we create a sheet and shove those planes that arrive there

     public class Runner{ public static void main(String[] args) { List<Flight> flightList = new ArrayList<Flight>(); flightList.add(new PassFlight()); flightList.add(new Freighter()); } } 

    Now, in principle, it is clear that we have a list with airplanes, and which they are not very important. For me, the main feature of abstract classes is that with the help of them you can set the logic of work without implementing it.

    • one
      Please do not forget to make out the code. - Nofate
    • Thanks, you need to learn more. - arachnoden

    Actually, the main difference between an abstract class and an ordinary one is only that it is impossible to create an object in an abstract class and therefore it is intended only for redefinition. And your first example is some kind of wrong, because there is no connection between the Addition, Substraction and Operation classes. An example can be seen, for example, here .

    • in fact, I cannot understand what the connection between them gives me, if separately they also work. the methods defined in the abstract class still need to be rewritten again in the children, for me so far the abstract class looks like "a very cool thing without which, in principle, you can do." - arachnoden

    This is a cross between an interface and a regular class. It differs from a class by the impossibility of creating instances, and from the interface by the possibility of fully declaring methods. it is convenient when there is a common method for a certain set of classes, but the rest must be overridden.