Please someone should explain this code line by line I can't understand ,thanks. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Please someone should explain this code line by line I can't understand ,thanks.

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(); } } //Beep!

30th Aug 2017, 5:50 AM
Sampson Joshua (Jozy)
Sampson Joshua (Jozy) - avatar
7 Answers
+ 10
Because the horn method is defined as: void horn() { System.out.println("Beep!"); // prints Beep! } And you call it with this statement: v2.horn(); When you call the method, next thing is to go to the place where it is defined and to execute whatever is stated there. And this is in your case the command System.out.println("Beep!"); which simply prints 'Beep!' to the console.
30th Aug 2017, 7:22 AM
Tashi N
Tashi N - avatar
+ 8
class Vehicle is a class with the attributes maxSpeed, wheels, color, fuelCapacity and a method horn (). In the main method you create two different Vehicle objects, v1 and v2. Then you try to assign a value to v1's color attribute and call the horn method on v2, which output 'Beep!' to the console. If you need further explanations, pls post which lines exactly you're struggling with.
30th Aug 2017, 6:22 AM
Tashi N
Tashi N - avatar
+ 6
It could set the value red to the attribute color. But you shouldn't access it like this from another class. It's better to use a setter (or if you like to improve your skills and do it like it's best practice: a builder). Maybe you should continue the Java course. Setters are explained in the chapter 'Classes and Objects', lesson 4.
30th Aug 2017, 2:36 PM
Tashi N
Tashi N - avatar
+ 4
I now understand but,why does this print Beep?
30th Aug 2017, 6:51 AM
Sampson Joshua (Jozy)
Sampson Joshua (Jozy) - avatar
+ 4
its like a horn in real life you know its there but it dosent return beep unless you press v2.horn() button :) 🚗
30th Aug 2017, 7:43 AM
D_Stark
D_Stark - avatar
+ 4
thanks
30th Aug 2017, 2:36 PM
Sampson Joshua (Jozy)
Sampson Joshua (Jozy) - avatar
+ 3
where I have v1.color="red"; how does this function too?
30th Aug 2017, 2:31 PM
Sampson Joshua (Jozy)
Sampson Joshua (Jozy) - avatar