Java中的“抽象类”是什么?


当前回答

抽象类不能直接实例化,但必须从抽象类派生才能使用。一个类必须是抽象的,如果它包含抽象方法:或者直接

abstract class Foo {
    abstract void someMethod();
}

或间接地

interface IFoo {
    void someMethod();
}

abstract class Foo2 implements IFoo {
}

然而,一个类可以是抽象的,而不包含抽象方法。这是一种防止直接瞬化的方法,例如。

abstract class Foo3 {
}

class Bar extends Foo3 {

}

Foo3 myVar = new Foo3(); // illegal! class is abstract
Foo3 myVar = new Bar(); // allowed!

抽象类的后一种风格可以用来创建“类接口”类。与接口不同,抽象类允许包含非抽象方法和实例变量。您可以使用它为扩展类提供一些基本功能。

另一种常见的模式是在抽象类中实现主要功能,并在由扩展类实现的抽象方法中定义部分算法。愚蠢的例子:

abstract class Processor {
    protected abstract int[] filterInput(int[] unfiltered);

    public int process(int[] values) {
        int[] filtered = filterInput(values);
        // do something with filtered input
    }
}

class EvenValues extends Processor {
    protected int[] filterInput(int[] unfiltered) {
        // remove odd numbers
    }
}

class OddValues extends Processor {
    protected int[] filterInput(int[] unfiltered) {
        // remove even numbers
    }
}

其他回答

它是一个不能被实例化的类,并且强制实现类尽可能地实现它概述的抽象方法。

抽象类不能直接实例化,但必须从抽象类派生才能使用。一个类必须是抽象的,如果它包含抽象方法:或者直接

abstract class Foo {
    abstract void someMethod();
}

或间接地

interface IFoo {
    void someMethod();
}

abstract class Foo2 implements IFoo {
}

然而,一个类可以是抽象的,而不包含抽象方法。这是一种防止直接瞬化的方法,例如。

abstract class Foo3 {
}

class Bar extends Foo3 {

}

Foo3 myVar = new Foo3(); // illegal! class is abstract
Foo3 myVar = new Bar(); // allowed!

抽象类的后一种风格可以用来创建“类接口”类。与接口不同,抽象类允许包含非抽象方法和实例变量。您可以使用它为扩展类提供一些基本功能。

另一种常见的模式是在抽象类中实现主要功能,并在由扩展类实现的抽象方法中定义部分算法。愚蠢的例子:

abstract class Processor {
    protected abstract int[] filterInput(int[] unfiltered);

    public int process(int[] values) {
        int[] filtered = filterInput(values);
        // do something with filtered input
    }
}

class EvenValues extends Processor {
    protected int[] filterInput(int[] unfiltered) {
        // remove odd numbers
    }
}

class OddValues extends Processor {
    protected int[] filterInput(int[] unfiltered) {
        // remove even numbers
    }
}

什么是抽象类? 好的!让我们举个例子,你对化学了解不多,我们有一个元素碳(符号C)。碳有一些基本的原子结构,你不能改变,但用碳你可以制造很多化合物,如(CO2),甲烷(CH4),丁烷(C4H10)。

所以这里碳是抽象类,你不想改变它的基本结构,但你想让他们的孩子(CO2,CH4等)使用它。但是以他们自己的方式

An abstract class is one that isn't fully implemented but provides something of a blueprint for subclasses. It may be partially implemented in that it contains fully-defined concrete methods, but it can also hold abstract methods. These are methods with a signature but no method body. Any subclass must define a body for each abstract method, otherwise it too must be declared abstract. Because abstract classes cannot be instantiated, they must be extended by at least one subclass in order to be utilized. Think of the abstract class as the generic class, and the subclasses are there to fill in the missing information.

它什么都不做,只是提供一个公共模板,它将被它的子类共享