Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在另一个新的侧面中使用“new”作为参数?_Java - Fatal编程技术网

Java 如何在另一个新的侧面中使用“new”作为参数?

Java 如何在另一个新的侧面中使用“new”作为参数?,java,Java,下面是一个示例,它显示了组合优于继承。我不明白的是Testbus类中的一段代码。那是 new Bus(new PrototypeEngine1()).drive(); 我不熟悉上面的代码风格。如何在另一个新的方面使用一个新的参数?这种类型的传递参数或参数叫什么?有名字吗 下面是我在遇到TestBus类之前一直遵循的完整上下文 有一个类引擎,它有一个启动方法。还有另一个类总线,它有一个方法驱动 //dummy class or prototype class for actual engine

下面是一个示例,它显示了组合优于继承。我不明白的是Testbus类中的一段代码。那是

new Bus(new PrototypeEngine1()).drive();
我不熟悉上面的代码风格。如何在另一个新的方面使用一个新的参数?这种类型的传递参数或参数叫什么?有名字吗

下面是我在遇到TestBus类之前一直遵循的完整上下文

有一个类引擎,它有一个启动方法。还有另一个类总线,它有一个方法驱动

//dummy class or prototype class for actual engine

class PrototypeEngine1{

public boolean start(){
     // do smething
return true;
}
}

class Bus extends PrototypeEngine1 {
public void drive(){
boolean isStarted = false
boolean isStarted = super.start();

if(isStarted == true) {
// do something
}else {
    // do something
}
}
}
创建包含engine引用的Buss类

class Bus {
   private Engine engine;
   public Bus ( Engine engine)
    {
      this.engine = engine;
 }

   public void drive(){

    boolean isStarted = false;
     isStarted = engine.start();
    if(isStarted == true) {
    // do something
    }else {
        // do something
    }
   }
}

class TestBus{
public void testDrive(){
   new Bus(new PrototypeEngine1()).drive();
}
}

您可以在新实例创建构造函数调用中创建新实例。除了可读性之外,创建一个新变量并传递它没有什么区别

new Bus(new PrototypeEngine1().drive());
新建PrototypeEngine1->创建PrototypeEngine1的新对象

新建PrototypeEngine1.drive->在PrototypeEngine1类中为我创建的对象调用方法drive

new Busnew PrototypeEngine1.drive->创建总线的新实例。提供从2返回的值,供总线内的构造函数使用

此外,由于PrototypeEngine1类中没有drive方法,因此代码也不会编译。新操作符用于创建类的实例。在new Bus new PrototypeEngine1.drive中发生的事情是,PrototypeEngine1的一个实例正在被创建为new Bus的一个参数

为了说明这个概念,让我们以一步一步的方式重构单行代码:

PrototypeEngine1 engine = new PrototypeEngine1();
Bus bus = new Bus(engine);
bus.drive();

这些代码行实际上相当于原来的一行代码。

您发布的代码实际上不会编译,因为在new Bus new PrototypeEngine1.drive中,PrototypeEngine1没有驱动方法。你是说新的总线新的原型引擎1.drive?另外,我怀疑你的第一节公交车是要装标准引擎或类似的东西。请显示实际编译且格式正确的。您的类不清楚。无论如何。。。您可以在此处使用new操作符,因为它仅用于创建对象。您可以首先创建PrototypeEngine1对象并分配给变量,然后在新总线中使用该变量。。它只是传递总线构造函数作为参数执行其操作的PrototypeEngine的新实例。看在上帝的份上,请为这个问题添加一些有意义的标题。修改了PrototypeEngine1代码new Busnew PrototypeEngine1.drive实际上非常简单。它首先创建一个新的PrototypeEngine1对象,并调用该对象的方法drive。然后它获取驱动器的返回值,并将其传递给新总线的构造函数。