Java abstract class concept and usage example analysis

  • 2021-01-14 06:00:44
  • OfStack

This article illustrates the concept and usage of Java abstract classes. To share with you for your reference, as follows:

Abstract: is a general description of a thing

Abstract method: A method styled abstract that only declares the return data type, method name, and required parameters. It does not have a function body. Such as abstract void study ();

Abstract class features:

1. The abstract class does not necessarily contain abstract methods; But abstract method 1 must be in an abstract class.
2. An abstract class has no real function and can only be used to derive subclasses
An abstract class can contain constructors, but constructors cannot be declared as abstractions. Member methods in an abstract class include generic methods and abstract methods
4. Both abstract methods and abstract classes must be modified with the abstract keyword
5. An abstract class cannot create an object using new. It must be called by the subclass object after the subclass has duplicated all the abstract methods.
6. For abstract methods in abstract classes to be used, subclasses must copy all abstract methods and then create subclass calls. A subclass is still an abstract class if it only duplicates part of the abstract methods.
7. The abstract method must be public or protected (because if it is private, it cannot be inherited by a subclass, and the subclass cannot implement the method).


abstract class Student// An abstract class 
{
  private String name;
  private int age;
  abstract void study();// Abstract methods 
  Student(String name,int age)
  {
    this.name=name;
    this.age=age;
  }
}
class GaoZhongStudent extends Student
{
   private String xuehao;
  GaoZhongStudent(String name,int age,String xuehao)
  {
   super(name,age);// Executes the parent class constructor 
   this.xuehao=xuehao;
  }
   public void study()
   {
   System.out.println("study gaozhong");
   }
}
class ChuZhongStudent extends Student
{
   ChuZhongStudent(String name,int age)
  {
   super(name,age);
  }
   public void study()
   {
   System.out.println("study chuzhong");
   }
}
class abstractDemo
{
  public static void main(String[] args)
  {
    ChuZhongStudent p1=new ChuZhongStudent("zhangsan",20);
    p1.study();
    GaoZhongStudent p2=new GaoZhongStudent("lisi",20,"yaohua001");
    p2.study();
  }
}

More java related content interested readers can see the site: "Java object-oriented programming introduction and advanced tutorial", "Java data structure and algorithm tutorial", "Java operation DOM node skills summary", "Java file and directory operation skills summary" and "Java cache operation skills summary"

I hope this article described to everyone java programming help.


Related articles: