Explanation of the concept of Java abstract class

  • 2021-06-28 12:45:01
  • OfStack

To put it simply

An abstract class is usually used as the topmost parent of a class, representing the concrete things in reality with the lowest class, and the commonality of all things in that class with the topmost class.Modify a class with the abstract keyword class, which is called an abstract class.

There are abstract classes so there must be abstract methods. What are abstract methods?

An abstract method is one that has a name, a list of formal parameters, a return value, and no body.

The relationship between abstract methods and abstract classes?

Any method without a body must be decorated with the keyword abstract as an abstract method.

Any class containing an abstract method must be declared as an abstract class.


abstract class A{
 abstract public void f();// With abstract methods 1 Must be an abstract class 
}
abstract class B{
 public void f(){
// Abstract class does not 1 There must be abstract methods 
}
}

We can see from the example that there is no method body in the A class method, so the keyword abstract is used and the A class must also be declared abstract.

Polymorphism in abstract classes:


abstract class a{
 abstract public void f();
}
class B extends A{
public void f(){
 System.out.println("BBB");
}
}
public class text{
public static void main(String[] args){
 A aa=new A();// Error, abstract class cannot be instantiated 
 B bb=new B();//ok
 bb.f()//OK
 A aa;// Abstract classes can be defined 1 References to abstract classes, but not definable 1 Abstract class object. 
 aa=bb;// References to abstract classes are used to point to subclasses that are truly implemented, and polymorphisms are used to call their subclass methods. 
 aa.f();
}
}

summary


Related articles: