+ 2

Can anyone tell me why this code not giving any output

public class Vehicle { public String color; class Program { public void main(String[ ] args) { Vehicle v1 = new Vehicle(); v1.color = "Red"; System.out.println(v1.color);} } }

1st May 2020, 8:52 AM
Shivam Rawal
6 odpowiedzi
+ 5
main() should be static. If you define another public class you should define it in a separate file or inside another class: public class Program{ public static class Vehicle { public String color; } public static void main(String args[]) { Vehicle v1 = new Vehicle(); v1.color = "Red"; System.out.println(v1.color); } }
1st May 2020, 9:06 AM
andriy kan
andriy kan - avatar
+ 2
First you have to build an object (instancisting) from your class for example with new statement. It looks like here: https://www.sololearn.com/learn/Java/2155/
1st May 2020, 10:47 AM
JaScript
JaScript - avatar
+ 1
or //public class Vehicle { public String color; } class Program { public static void main(String[ ] args) { Vehicle v1 = new Vehicle(); v1.color = "Red"; System.out.println(v1.color); } //} }
1st May 2020, 10:26 AM
zemiak
+ 1
Your main() method must be static. Because it is the entry point of your program. Java interpreter will invoke the main() method with out creating the object of "Program" class.
2nd May 2020, 9:54 AM
Dasarath Singh
+ 1
Program class is inside the Vehicle class and main() method is inside the Program class which is the entry point. When you run the code java interpreter will look main() inside the Vehicle class and it is unable to find the main() method. So separate the Vehicle class from Program class.
2nd May 2020, 10:48 AM
Dasarath Singh
0
Tysm
1st May 2020, 9:59 AM
Shivam Rawal