无法实例化抽象类

时间:2015-05-22 12:10:34

标签: java oop instantiation

package InterfaceAbstractOverloadingOverriding;

public class instrumentExecute 
{

    public static void main(String[] args) 
    {
         GuitarAbstract g = new GuitarAbstract();
         NewGuitar ng = new NewGuitar(); 
         g.play();
         ng.play();

         g = new GuitarAbstract(7);
         ng = new NewGuitar(5);
         g.play();
         ng.play();
    }
}

我无法实例化GuitarAbstract

错误:

Cannot instantiate the type GuitarAbstract.GuitarAbstract is an abstract class.

1 个答案:

答案 0 :(得分:2)

You can't directly instantiate an abstract class, but you can instantiate an anonymous class for your abstract class.

For example, given the following abstract class:

class GuitarAbstract {

  public abstract void play();
}

You can create an anonymous class like so:

GuitarAbstract guitar = new GuitarAbstract() {

  @Override
  public void play() {
    System.out.println("Playing guitar!");
  }
};