I have tried to run this Java-code but there are some errors in it. I wanted to set default parameters of the class and then class constructor. But something is wrong in it. Help me please to solve this problem.
public class Main{
public static void main(String[] args){
Vehicle bmw_m5 = new Vehicle("BMW", "M5_competition", 2012);
System.out.println(bmw_m5.name); System.out.println(bmw_m5.model); System.out.println(bmw_m5.release_year);
}
}
class Vehicle{
String name;
String model;
int release_year;
this.name = "undefined";
this.model = "undefined";
this.release_year = 0;
Vehicle(String name, String model, int release_year){
this.name = name;
this.model = model;
this.release_year = release_year;}
}
Here is the code itself.
public class Main{
public static void main(String[] args){
Vehicle bmw_m5 = new Vehicle("BMW", "M5_competition", 2012);
System.out.println(bmw_m5.name);
System.out.println(bmw_m5.model);
System.out.println(bmw_m5.release_year);
}
}
class Vehicle{
String name = "undefined";
String model = "undefined";
int release_year = 0;
Vehicle(String name, String model, int release_year){
this.name = name;
this.model = model;
this.release_year = release_year;}
}
Should work if you remove "this" outside of methods and specify your default values when you declare the variables.
Depending on the use case you also might want to look into access modifiers. So for example you could make the instance variables private. Afterwards create getter/setter methods for each variable. A default constructor that initializes the object with default values and a constructor as you alreade have. If an objekt is then already created you could later on modifiy its instance variable via setters.