A constructor is a special method used to initialize a newly created object and is called automatically when an object is created. A constructor has the same name as the class and does not have a return type.
Example:
public class Car {
private String model;
private int year;
public Car(String model, int year) {
this.model = model;
this.year = year;
}
}
A method is a block of code that performs a specific task and returns the result of the task. A method has a return type and can be called explicitly by the code.
Example:
public class Car {
private String model;
private int year;
public Car(String model, int year) {
this.model = model;
this.year = year;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
}