📜  Java抽象类和抽象方法的区别

📅  最后修改于: 2021-09-14 01:33:55             🧑  作者: Mango

Abstract 是仅适用于方法和类而不适用于变量的修饰符。即使我们没有实现,我们仍然可以声明一个带有抽象修饰符的方法。即抽象方法只有声明,没有实现。因此,抽象方法声明应该强制以分号结束。

插图:

public abstract void methodOne(); ------>valid
public abstract void methodOne(){} ------->Invalid

例子:

Java
// Java Program to illustrate Abstract class
  
// Abstract Class
// Main class
abstract class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
  
        // Creating object of class inside main() method
        GFG gfg = new GFG();
    }
}


Java
// Java Program to Illustrate Abstract Method
  
// Main class
// Abstract class
abstract class Parent {
  
    // Methods of abstract parent class
    public abstract void methodOne();
    public abstract void methodTwo();
}
  
// Class 2
// Child class
class child extends Parent {
  
    // Method of abstract child class
    public void methodOne() {}
}


输出:

输出说明:

即使该类不包含任何抽象方法,我们仍然可以将该类声明为抽象类,它是一个抽象类,它也可以包含零个抽象方法。

图 1:

class Parent 
{  // Method of this class 
   public void methodOne();
}

输出:

Compile time error.
missing method body, or declared abstract
public void methodOne();

图 2:

class parent {
   // Method of this class
   public abstract void methodOne() {}
}

输出:

Compile time error.
abstract method cannot have a body.
public abstract void methodOne(){}

图 3:

class parent {

   // Method of this class
   public abstract void methodOne();
}

输出:

Compile time error.
Parent is not abstract and does not override abstract method methodOne() in Parent class
Parent

例子:

Java

// Java Program to Illustrate Abstract Method
  
// Main class
// Abstract class
abstract class Parent {
  
    // Methods of abstract parent class
    public abstract void methodOne();
    public abstract void methodTwo();
}
  
// Class 2
// Child class
class child extends Parent {
  
    // Method of abstract child class
    public void methodOne() {}
}

输出:

现在让我们在充分了解它们后,最终总结它们之间的差异。

Abstract classes Abstract methods
Abstract classes can’t be instantiated. Abstract method bodies must be empty.
Other classes extend abstract classes. Sub-classes must implement the abstract class’s abstract methods.
Can have both abstract and concrete methods. Has no definition in the class.

Similar to interfaces, but can 

  • Implement methods
  • Fields can have various access modifiers
  • Subclasses can only extend one abstract class
Has to be implemented in a derived class.