This is the fourth day of my participation in Gwen Challenge

An abstract class

Before we study abstract classes, we need to know why abstract classes are studied, and what they are used for. With these two questions in mind, let’s meet the next part of our study.

First question: Why do we learn abstract classes?
When we define classes, we often write methods for them that describe the behavior of the class. If we require different shaped area, we can define a Shape, but different Shape subclasses meter area method is different, our Shape doesn't know how to calculate each different shapes of the graphics area, then we can use an abstract class, make the abstract class contains area of the common behavior, By rewriting the getArea() method, we can find the areas of different shapes.Copy the code

Maybe you don’t understand it by now, but let’s do it by example.

Before the second question, let’s look at some of the rules for abstract classes and methods.

Rules for abstract classes and methods

  • Abstract classes and methods must be qualified with the abstract keyword, and abstract methods cannot declare method bodies.
Public abstract class Test {public Test(){} public abstract void showAll(){//error} public abstract void Print(); }Copy the code
  • An abstract class may or may not contain an abstract method, but a class containing an abstract method must be an abstract class.
Public abstract class Test {public Test(){} public void speak (String s){ System.out.println(s); } public abstract void Print(); } public class Test {public Test(){} public void Print(); //error }Copy the code
  • Abstract classes cannot be instantiated, that is, they cannot invoke the constructor to create objects using the new keyword. However, an abstract class can have constructors that are used primarily for subclass calls.
Which brings us to our second question, what are abstract classes for?
Abstract classes can not create instances, can only be inherited as a parent class, and use abstract classes, can play the advantages of polymorphism, make the program more flexible. An abstract class is a higher level abstraction that abstracts from subclasses that share the same characteristics and serves as a generic template for subclasses. Abstract classes represent a kind of template design, which is one of the design patterns. (If you want to know about design patterns, I suggest you go to SITE B to find videos to learn, which is still very useful for our work.)Copy the code

Abstract methods can only be overridden by subclasses. Final classes cannot be overridden. Final methods cannot be overridden. Therefore, you can never use abstract and final together.

The above is my abstract class of some shallow solution, if there is wrong or missing, welcome to comment on correction.

Next time we’ll look at interfaces related to abstract classes.