Could someone explain why this works.
I have 2 classes in Eclipse.
A Class called “Car” contains the following code..
public class Car {
public void printOut(String variable1){
System.out.println("Hello " +variable1);
}
}
and another class , which is where my ‘main’ is, is called “House”, the code inside it is
import java.util.Scanner;
class House {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
Car carObject = new Car();
System.out.println("Enter name here: ");
String variable2 = input.nextLine();
carObject.printOut(variable2);
}
}
When I run the code, it works, it writes “Enter name here” and when I type it out, it proceeds to say “Hello “name entered” “
My question is, do ‘variable1’ and ‘variable2’ have any relation to eachother, other than that they’re both of String class.
because i’m confused as to why the code compiles correctly.
To me, it looks like variable 1 has no correlation to variable2, even though they’re both of String class, it doesn’t look like they ever interact with one another, and variable1 isn’t used in the “House” class at all, yet it still knows to compile whatever I’ve entered.
It’s as if ‘variable1’ is replaced by ‘variable2’ and whatever variable2 contains gets printed out.
The method definition in class
Caris sort of a prototype for when you use it. Have you ever been taught functions in maths with a ‘black box’? You put in a number, and get output. So, you enter 3, if the function is f(x) = Xx2, the output will be 6. Before you call the method, var2 is completely different from var1. In the method however, var2 is passed and replaces all var1s you use in the method. Don’t worry, I didn’t get this either when I started Java