Creating two objects at the same time in java

I created a class called "Car'and", I have this code. Car c=new Car(), yourCar;

and I don't know what "yourKar" means. Is the same as Car myCar = new Car(); Car yourCar = new Car();

? I cannot understand after the comma.

 package ex2_datatypecasting02;


class Car{
    String name = "car";
    String print() {
    return name;
    }
}
class Bus extends Car{
    String name = "bus";
    String print() {
    return name;
    }
}
public class CastingExam {
public static void main(String[] args) {
    Car myCar = new Car(),yourCar;
    Bus myBus = new Bus(),yourBus;
    System.out.println(myCar.print());
    System.out.println(myBus.print());
    yourCar = myBus;
    yourBus = (Bus)yourCar; 
    System.out.println(yourBus.print());
    } 
}

      

+3


source to share


2 answers


You can declare multiple variables of the same type on the same line by separating them with a comma ( ,

). How:

//declare three integers
int x, y, z;

      

which is equivalent to:

int x; // declare x
int y; // declare y
int z; // declare z

      

So, I have three integers declared , but I have not initialized them . You can also initialize one or more of them, for example:



//declare three integers, initialize two of them
int x = 1, y, z = 4;
//  ^         ^ initialized

      

which is equivalent to:

int x = 1; // declare and initialize x
int y;     // declare y
int z = 4; // declare and initialize z

      

Here we have declared three variables and initialized x

both z

with 1

and 4

respectively.

Thus, the statement declares two variables Car

: c

and yourCar

, and c

initializes a new car yourCar

- not .

+4


source


As Willem well explained, this statement is:

Car myCar = new Car(),yourCar;

      

It is valid and allows you to declare two variables Car

, but initializes only one of them: myCar

.
yourCar

here really null

.



I would like to add that this way of doing reserves for you lines, but is really error prone.
To get the best readability of your code, you must declare each variable on a separate line:

Car myCar = new Car();
Car yourCar;

      

It produces the same result, but it is much clearer.

+2


source







All Articles