Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
example of what a constructor is
class Example {
/*
A car has the following attributes:
1) number of wheels
2) tire type
A car has the following behaviors:
1) it can run at a certain speed
2) it can park
*/
static class Car {
private String tireType = "Nokia@N"; // Nokia@N
// An example of "constructor"
// A constructor has the following properties
// 1) It looks like a method
// 2) But, it's special in that the "method name"
// is the same as the class name. e.g. Car
// 3) Yeah, it looks like a method, but it has
// NO "return type"
// 4) Constructor is special because it's always
// run when the class is "new"ed (e.g. object instantiation)
private int numWheels = 18; // 18
// Constructor choice when no input parameter
Car()
{
numWheels = 8;
}
// Constructor choice when there is an input parameter of type int
Car(int inputNumWheels)
{
numWheels = inputNumWheels;
}
public int getNumWheels()
{
return numWheels;
}
};
public static void main(String[] args) {
Car car1 = new Car(); // an example of object instantiation
Car car2 = new Car(10); // another object instantiation
System.out.println(car1.getNumWheels());
System.out.println(car2.getNumWheels());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment