Creating Objects

Objects

Creating Objects

🙋 Need help? Ask an expert now!

We have already worked with objects in previous chapters; they are some of the building blocks in Java. Let's go back to the basics and explore objects from their foundation. There are three properties that each object has. First, each object has a unique "identity" that makes it distinct from any other. Second, each object has a current "state", meaning it currently contains a value that has the ability to change. And third, an object has a "behavior" which enables it to call and run methods. Let's create an object below.

ObjectTest.java
package exlcode;

public class ObjectTest {

  private String exampleVariableOne;

  // constructor of the class
  public ObjectTest(String exampleVariableOne) {
    this.exampleVariableOne = exampleVariableOne;
  }

  public void print(){
    System.out.println(exampleVariableOne);
  }
}
ObjectsExample.java
package exlcode;

public class ObjectsExample {

  public static void main(String[] args) {
    // creates a new object of the test class
    // since the constructor of the ObjectTest class takes in
    // one String parameter, "Hello World!" is inside the parentheses
    ObjectTest objectTest = new ObjectTest("Hello World!");
    objectTest.print();
  }
}

Objects refer to a particular instance of a class. In Java, this allows us to create particular instances of classes and store them in variables called objects. The syntax for creating most objects is as follows:

ClassName variableName = new ConstructorName(parameters);

As you have seen previously, the constructor name is the same as the class name. Objects can have parameters inside the parenthesis, depending on the constructor of the other class.

When you create a new ArrayList and use the reserved word new, it makes an object from the original ArrayList class and stores it inside the name of your ArrayList. This is why you can use dot notation (.) and directly call methods and variables that exist in the original ArrayList class as they also exist in the instance you created. However, you still need a "main class" containing a functioning main method in order for your program to compile and run. Have you tried creating an object of the class itself in the main method? We will see these later in the course!

Edit Me on GitHub!

Application Question

Which statement would we use to create an object from ExampleClass?