170k views
2 votes
In Java, write a constructor in such a way that a Vehicle object with color and type can be constructed directly via, say:

Vehicle("Pink", "Car");

User Findango
by
5.3k points

1 Answer

2 votes

Answer:

Step-by-step explanation:

  • In Java, a Constructor is similar to that of a method which will be called when creating a new object for the class.
  • There is no return type for a Constructor.
  • public Vehicle (String color, String type)

{

colourName = color;

typeName = type;

}

  • In Java, you can use new operator to create an object of a class.
  • Here, the object for the class Vehicle is created like Vehicle vehicle = new Vehicle("Pink", "Car");
  • When creating the object of the class, the new operator calls the constructor.
  • If there is no constructor defined explicitly, a default constructor is created by the compiler.
User DerBenniAusA
by
5.3k points