Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making two object at the same time in java

Tags:

java

I've made a class named 'Car'and I have this code. Car c=new Car(), yourCar; and I don't know what 'yourCar' means Is is same asCar myCar = new Car(); Car yourCar = new Car(); ? I can't 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());
    } 
}
like image 489
최희영 Avatar asked Apr 08 '26 02:04

최희영


1 Answers

You can declare multiple variables of the same type on one line by separating them with a comma (,). Like:

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

which is equivalent to:

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

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

//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 initializes x and z with 1 and 4 respectively.

So the statement declares two Car variables: c and yourCar, and c is initialized with a new car, yourCar is not.

like image 177
Willem Van Onsem Avatar answered Apr 09 '26 16:04

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!