Outside Resources:
TheNewBoston – Using Multiple Classes
TheNewBoston – Many Methods and Instances
TheNewBoston – Constructor Methods
A class is a type of object.
Objects are “things” stored in memory that have both attributes (variables) and methods.
Objects offer a lot of complexity, flexibility, and power.
Defining a Class
You have to create a blueprint for your objects before you can create objects. The class is the blueprint.
This simple example class Item has two attributes. This means that any time an Item object is created, it can contain two variables that describe it.
public class Item { int idNumber; String description; }
Creating Object Instances
You can create Item object instances like so:
(These instances must be created in a different class – in this case, the other class is called Main)
public class Main { public static void main(String[] args) { Item item1 = new Item(); item1.description = "spatula"; item1.idNumber = 12345; Item item2 = new Item(); item2.description = "shovel"; item2.idNumber = 67890; } }
As you can see, this creates two objects named item1 and item2. The program also gives the objects’ attributes some values.
When objects are instantiated (created), the code follows this pattern:
ClassName objectName = new ClassName();
The object is declared on the left, and on the right a constructor method (notice the parentheses) is called to instantiate the object in memory.
Constructor methods always have the same name as the class itself.
(By convention, class names are capitalized and object names start with a lowercase letter.)
The following accomplishes the same thing as the above example:
ClassName objectName; objectName = new ClassName();
This time, the object is declared separately in the first line and then instantiated at a later time. This is commonly done to give the object more of a global scope.
Accessing Object Methods and Attributes
When you access a method or attribute of an object, you follow this pattern:
objectName.parameterName objectName.methodName()
The object ‘s name comes first, followed by a dot. Then you type the name of the parameter or method. Methods always end with parentheses.
Note that we’re using the name of the object, not the name of the class*.
*If the method is static, then you can use the name of the class instead.