constructor query | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

constructor query

public class Program { public static void main(String[] args) { Vehicle colType = new Vehicle(); Vehicle v1 = new Vehicle("LEATHER"); colType.setColor(); System.out.println("final color :" + colType.getColor()); } } public class Vehicle { private String color; Vehicle(String seatType){ System.out.println("seat material:" + seatType); } public void setColor(){ this.color = "red"; } public String getColor(){ return color; } } please let me know what am i doing wrong ? can't we declare an object "colType "to Vehicle class when constructor is defined?

1st Oct 2017, 3:28 AM
rohit
5 Answers
+ 5
A default constructor is only supplied if no Constructor was created for the class. Here you created one that takes a String as its arguments. So, there is no, no argument constructor. You will need to define one on your own, like so: Vehicle(){}
1st Oct 2017, 4:01 AM
Rrestoring faith
Rrestoring faith - avatar
+ 16
Change (line 4) what is your argument? Vehicle colType = new Vehicle("Leather");
1st Oct 2017, 3:38 AM
Nithiwat
Nithiwat - avatar
1st Oct 2017, 3:43 AM
Nithiwat
Nithiwat - avatar
+ 1
Vehicle colType = new Vehicle(); here colType is normal object for Vehicle class(not for constructor.. its for setter method) .. i am not passing any argument .. cant we implement like this.? when constructor is defined , can't we have other methods in class?
1st Oct 2017, 3:48 AM
rohit
+ 1
thanks for explanation @Rrestoring faith
1st Oct 2017, 4:25 AM
rohit