Digital Dave Digital Dave - 6 months ago 11
Java Question

How is it possible to use a "new" as parameter in side another new?

Below is an example which kinda shows the advantage of composition over inheritance. All I dont understand is the piece of code in class Testbus. which is

new Bus(new PrototypeEngine1()).drive();


I am not familiar with the above style of code. How is it possible to use a "new" as parameter in side another new ? whats is this type of passing parameter or argument called? Is there a name for it ?

Below is the full context which I was following Until I encountered "TestBus" class.

There is a class engine it has a method method start(). There is another class Bus it has a method drive().

//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
}
}
}


Creating Buss Class which has a reference of engine inside it

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();
}
}

Answer

The new operator is used to create an instance of a class. What's happening in new Bus(new PrototypeEngine1()).drive() is that an instance of PrototypeEngine1 is being created as an argument to new Bus().

To illustrate this concept, let's refactor the single line of code in step by step manner:

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

These lines of code are practically equivalent to that original one line of code.

Comments