Would this work?
class Cars{
Cars(int speed, int weight)
}
I am just trying to figure out the constructor. If it is called like a method t
You are probably not understanding the correct use of Constructors.
Constructor
A constructor is used in the creation of an object that is an instance of a class. Typically it performs operations required to initialize the class before methods are invoked or fields are accessed.
Constructors are used as a way to instantiate a new Instance of that Object. They don't have to have any instance variable inputs. Instance variables are declared so multiple methods within a particular class can utilize them.
public class Foo{
String x;
int y;
Foo(){
//instance variables are not set therefore will have default values
}
void init(String x, int y){
//random method that initializes instance variables
this.x = x;
this.y = y;
}
void useInstance(){
System.out.println(x+y);
}
}
In the example above, the constructor didn't set the instance variables, the init() method did. This was so that useInstance() could use those variables.
In your example speed and weight are not instance variables because their scope is limited to the constructor. You declare them outside in order to make them visible throughout the whole class (i.e. throughout objects of this class). The constructor has the purpose of initialising them.
For example in this way:
public class Car
{
// visible inside whole class
private int speed;
private int weight;
// constructor parameters are only visible inside the constructor itself
public Car(int sp, int w)
{
speed = sp;
weight = w;
}
public int getSpeed()
{
// only 'speed' and 'weight' are usable here because 'sp' and 'w' are limited to the constructor block
return speed;
}
}
Here sp
and w
are parameters which are used to set the initial value of the instance variables. They only exist during the execution of the constructor and are not accessible in any other method.