Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java implicit methods/parameters?

im currently reading a book about programming Android and there is a nice little reference guide on Java in the beginning chapters. However, I stumpled upon something about implicit parameters that I did not quite understand.

He defines the class Car:

public class Car {
  public void drive() {
    System.out.println("Going down the road!");
  }
}

Then he continues on with this:

public class JoyRide {
 private Car myCar;

 public void park(Car auto) {
   myCar = auto;
 }

 public Car whatsInTheGarage() {
   return myCar;
 }

 public void letsGo() {
   park(new Ragtop()); // Ragtop is a subclass of Car, but nevermind this.
   whatsInTheGarage().drive(); // This is the core of the question.
 }
}

I just want to know how we can call drive() from the class Car when JoyRide is not an extension of Car. Is it because the method whatsInTheGarage() is of return type Car, and thus it "somehow" inherits from that class?

Thanks.

like image 238
yackyackyack Avatar asked Apr 08 '12 19:04

yackyackyack


People also ask

What is an implicit parameter?

What Are Implicit Parameters? Implicit parameters are similar to regular method parameters, except they could be passed to a method silently without going through the regular parameters list. A method can define a list of implicit parameters, that is placed after the list of regular parameters.

Can methods have parameters Java?

Parameters and ArgumentsInformation can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

Does a static method have an implicit parameter?

Static methods are those methods that are not called on objects. In other words, they don't have an implicit parameter.

What are parameters in Java methods?

In Java, a parameter is a variable name with type that is declared within the method signature. The list of parameters is enclosed in parenthesis. Each parameter consists of two parts: type name, and variable name.


1 Answers

Think about this piece of code:

whatsInTheGarage().drive();

as a shorthand for this:

Car returnedCar = whatsInTheGarage();
returnedCar.drive();

Is it clear now? All C-like languages with c-like syntax behave like this.

UPDATE:

myCar.drive();  //call method of myCar field

Car otherCar = new Car();
otherCar.drive();  //create new car and call its method

new Car().drive()  //call a method on just created object

public Car makeCar() {
  return new Car();
}

Car newCar = makeCar();  //create Car in a different method, return reference to it
newCar.drive();

makeCar().drive();  //similar to your case
like image 76
Tomasz Nurkiewicz Avatar answered Sep 22 '22 02:09

Tomasz Nurkiewicz