+ 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);} } }
6 Antworten
+ 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);
}
}
+ 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/
+ 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);
}
//}
}
+ 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.
+ 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.
0
Tysm