Java learning - Abstract classes, abstract methods with examples

Keywords: Java Attribute

This article will describe the knowledge points of abstract classes and methods in java, which is the simplest and most easily forgotten. In Java, if we want to represent an abstract class or method, we need to use abstract, its Chinese translation is "abstract".

Abstract classes and methods

First: Knowledge combing

1. Basic concepts:

In the concept of object-oriented, all objects are described by classes, but not all classes are used to describe objects. When a class does not contain enough information to describe a specific object, such classes are abstract classes.
Example: Shape is an abstract concept. Different subclasses have different methods for calculating shape area. Available
Abstract methods are implemented by different subclasses.

//The abstract class Shape
abstract public class Shape{
       abstract double area();//Abstract method
}

As can be seen from the example, abstraction is decorated with keywords == abstract==. There is a special method in abstract classes.
That is to say, the method decorated with the keyword== abstract== is called "abstract method".

2. The declarative format of abstract classes and methods:

3. The characteristics of abstract classes and methods:

(1) The abstract method does not allow direct instantiation, in other words, the abstract class cannot create objects, it can only be the parent class of other classes. But it can be transformed upwards to point to instantiation.
(2) An abstract method can only be declared and can not be implemented, that is, it has only method headers, but no method bodies and operation implementations.
For example: abstract double area();

4. The meaning of defining abstract classes lies in:

(1) Provide a common type for its subclasses (the parent reference points to the subclass object);
(2) Encapsulating duplicate content (member variables and methods) in subclasses;
(3) Designing the parent class as an abstract class can restrict the arbitrariness of the design of the child class by means of the parent-child inheritance relationship and avoid the instantiation of the meaningless parent class to a certain extent.

Focus on

Classes containing abstract methods can only be defined as abstract classes
As follows, when an abstract class is not defined, an error will be reported:


The correct code is:


Abstract classes do not necessarily contain Abstract methods.
Example

abstract public class Shape{
    public void girth(){
        System.out.println("The circumference of a circle is....");//General method
    }        
}

Membership methods in abstract classes can include general methods and abstract methods

abstract public class Shape{
    public void girth(){
        System.out.println("The circumference of a circle is....");//General method
    }
         abstract double area();//Abstract method
}

Abstract classes cannot be instantiated, even if they do not contain Abstract methods, they cannot create instances. The construction method of abstract class is mainly used to be called by its subclass.
Example:
Shape abstract classes do not contain Abstract methods:

abstract public class Shape{
    public void girth(){
        System.out.println("The circumference of a circle is....");//General method
    }       
}

When Shape is instantiated in the test class, the compiler will report errors:

After inheriting an abstract class, a class must implement all its abstract methods, otherwise it is also an abstract class. Different subclasses can implement different abstract methods of the parent class.

//Shape, the abstract parent class
abstract public class shape{
     abstract double area();//Abstract method
}

Circle, its subclass, has two approaches:

Solution 1: Rewrite the abstract method area(), so that the method can be realized

//Word Circle Class
public class Circle extends shape{
     //Attribute: radius r of a circle
     public double r;
     public Circle(double r){
            this.r=r;
   }
   //Override the area() method in the parent class
   public double area(){
          return(double)(3.14*r*r)
  }
}

Solution 2: Subclass Circle classes are also defined as abstract classes

public abstract class Circle extends Shape{
       //Attribute: radius r of a circle
      public double r;
      public Circle(double r){
      this.r=r;
      }
}

Even if the parent class is concrete, its children can be abstract. If Object is concrete, it can create abstract subclasses.
The abstract method cannot be modified with static and private; for classes, final and abstract can not be modified at the same time, because final keywords make classes non-inheritable, and abstract modified classes will have no meaning if they cannot be inherited. Together, the two will conflict.

The following usages can cause compiler errors:


A complete and accurate example of abstract classes

Declare an abstract class Shape with an abstract member method area(). Shape derives two subclasses, circular Circle class and rectangular Rectangle class. Shape declares the abstract method area(), which is implemented in two subclasses.
The code is as follows:
Shape, the abstract parent class

//Shape, the abstract parent class
abstract public class Shape{
  abstract double area();//Abstract method
}

Subclass Circle

//Subclass Circle
public class Circle extends Shape{
    //Attribute: radius r of a circle
    public double r;

    Circle(){
    }
    //Create a parametric constructor (parameter r)
    public Circle (double r){
        this.r=r;
   }

   public double getR(){
        return r;
   }
   public void setR(double r){
        this.r=r;
    }
    //Override the area () method in the parent class
    public double area (){
           return(double)(3.14*r*r);
    }    
}

Subclass Rectangle Rectangle

//Subclass Rectangle Rectangle
public class Rectangle extends Shape{
     //Property: Long length, wide width of rectangle
     public double length;
     public double wide;

     Rectangle(){
     }
     //Create a parametric constructor (with length and wide as parameters)
     public Rectangle(double length,double wide){
         this.length=length;
         this.wide=wide;
    }
    public double getLength() {
        return length;
    }
    public void setLength(double length) {
        this.length = length;
    }
    public double getWide() {
        return wide;
    }
    public void setWide(double wide) {
        this.wide = wide;
    }
    //Override the area () method of the parent class
    public double area(){
        return length*wide; 
    }   
}

Test class

//Test class
public class text {
    public static void main(String[] args) {
        // Method stub for TODO automatic generation
        Circle c=new Circle(3.5);
        Rectangle re=new Rectangle(6,5);
        //Call the area() method and output the result
        System.out.print("The area of a circle is"+c.area());
        System.out.print("The area of the rectangle is"+re.area());
    }

}

Posted by haku87 on Sat, 20 Jul 2019 21:30:12 -0700