java - 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();
}
}
解决方案
Honda 类是使用Default Constructor创建的
如果一个类不包含构造函数声明,则隐式声明一个没有形式参数且没有 throws 子句的默认构造函数。
public class Point { int x, y; }
相当于声明:
public class Point { int x, y; public Point() { super(); } }
所以Bike()
每次调用new Honda();
推荐阅读
- mysql - 带有 MySQL 的 Raspbian Spin Docker 容器
- python - 在只包含常量的文件中不使用类的优点/缺点?
- javascript - 如何从节点控制台调用异步方法?
- swift - 有没有更好的方法来构建许多不同的 URL?
- xml - 在 VS 2015 片段中添加多次 $selected$
- python - 尝试从多个帧创建视频
- zlib - 放气的 zlib 对象有多大?
- xcode - xcode 10,unity,vuforia Command CodeSign 失败,退出代码为非零
- android - Android Vision 文本扫描在 Xamarin.Android 中泄漏内存
- ios - 如果我有 IBOutlet 进行约束,复杂 UIView 的布局会有所不同