Lessons

Java tutorial

Java Constructors

A constructor runs when new creates an object. It has the class name and no return type. this refers to the object being built, which is how a parameter can fill a field of the same name.

Example

Edit the code and run it again. This runner stays in your browser and covers the syntax used in these lessons.

Output

Run the example to see output here.

What this code does

new City calls the constructor, which copies the two arguments into the new object's fields. label then prints the name and population.