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() {}
}
输出:
输出说明:
If a class contains at least one abstract method then compulsory the corresponding class should be declared with an abstract modifier. Because implementation is not complete and hence we can’t create objects of that class.
即使该类不包含任何抽象方法,我们仍然可以将该类声明为抽象类,它是一个抽象类,它也可以包含零个抽象方法。
图 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
If a class extends any abstract class then compulsory we should provide implementation for every abstract method of the parent class otherwise we have to declare child class as abstract.
例子:
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() {}
}
输出:
Note: If we declare the child as abstract then the code compiles fine, but the child of a child is responsible to provide an implementation for methodTwo().
现在让我们在充分了解它们后,最终总结它们之间的差异。
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
|
Has to be implemented in a derived class. |