首页 > 解决方案 > java程序中的抽象

问题描述

为什么输出如下?

自行车被创造出来

安全运行..

换档

因为我们没有Bike() 在任何地方调用方法。

abstract class Bike {
    Bike() {
        System.out.println("bike is created");
    }

    abstract void run();

    void changeGear() {
        System.out.println("gear changed");
    }
}

//Creating a Child class which inherits Abstract class  
class Honda extends Bike {
    void run() {
        System.out.println("running safely..");
    }
}

//Creating a Test class which calls abstract and non-abstract methods  
class TestAbstraction2 {
    public static void main(String args[]) {
        Bike obj = new Honda();
        obj.run();
        obj.changeGear();
    }
}

标签: javaconstructorabstract-class

解决方案


Honda 类是使用Default Constructor创建的

如果一个类不包含构造函数声明,则隐式声明一个没有形式参数且没有 throws 子句的默认构造函数。

 public class Point {
      int x, y;
 }

相当于声明:

public class Point {
      int x, y;
      public Point() { super(); }
 }

所以Bike()每次调用new Honda();


推荐阅读