Creating a constructor for car class
It is important to be able to set values for a class’s properties, in order to use them effectively. You will create a Constructor for the Car
class and ensure that its properties are set to some values.
Remember: The constructor of a class will always be called when we create an instance.
Este exercício faz parte do curso
Introduction to Object-Oriented Programming in Java
Instruções do exercício
- Create a constructor method for the
Car
class that takes no parameters. - Inside the constructor, set the
color
property to be a String"red"
- Inside the constructor, set the
year
to be an Integer2019
- Print out the
color
property of themyCar
object instance.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
class Main {
static class Car {
String color;
String model;
int year;
// Create constructor method
____() {
this.model = "camry";
// Assign the values for the model and year properties
____.____ = ____;
____.____ = ____;
}
}
public static void main(String[] args) {
Car myCar = new Car();
// Print the "color" property
System.out.println(____.____);
}
}