+ 6

Guys what is the vehicle v1= new vehicle (); and vehicle v2= new vehicle () ; used for i don't get it . please guys help...

public class Vehicle { int maxSpeed; int wheels; String color; double fuelCapacity; void horn() { System.out.println("Beep!"); } } class MyClass { public static void main(String[ ] args) { Vehicle v1 = new Vehicle(); Vehicle v2 = new Vehicle(); v1.color = "red"; v2.horn(); } }

15th Jan 2018, 10:31 AM
Franklyn Omeben
Franklyn Omeben - avatar
3 Réponses
+ 6
There are actually 2 objects of class here both v1 and v2 are instances of the same class Vehicle. v1 vehicle is red and has all the attributes of class Vehicle (it can also beep but it hasn't been called) v2 has no colour at the moment but the beep method was called so the car beeps this vehicle also has all the attributes of class Vehicle so basically you have 2 vehicles which are the same type of class Vehicle apart from 1 is red and the other is beeping 😜
15th Jan 2018, 11:32 AM
D_Stark
D_Stark - avatar
+ 9
Think the class definition is the project, the blueprint of a car. then to create a car you need the project. so.. Vehicle v1=new Vehicle means.. Vehicle v1 -> v1 is the car you are creating, and it's a object of type Vehicle =new Vehicle() -> generate an obj based on the Vehicle blueprint and save it as v1 obj so in short.. v1 is the car Vehicle is the blueprint of a car
15th Jan 2018, 10:51 AM
AZTECCO
AZTECCO - avatar
+ 3
"new" operator is used to create new object of given class. If you don't know what object nor class is, I'd refer you to Java tutorials in this app.
15th Jan 2018, 10:42 AM
Jakub Stasiak
Jakub Stasiak - avatar