Using Multiple Classes

Vocab Bar
Field A variable inside of a class (created outside of a method or constructor).
Constructor A block of code similar to a method that is used to create an object of the class.
Default Constructor A constructor generated by the computer when the programmer has not provided a constructor.

Making classes in IntelliJ only requires a few easy steps. First, make sure you see the following sidebar:

Next, right-click on src, and click New → Java Class. Name your class, and a new class template should be automatically constructed:

Note: Remember that if you want to change the class name, you need to change both the class name and the file name to avoid producing an error (the class name and file name must match).

Almost every class contains three crucial parts: methods, fields, and constructors. We have already worked with methods, and understand that they are a group of statements that combine to perform a specific operation. Fields are variables that are inside a class, but made outside of methods. Additionally, they are usually declared as private to limit who has access to these variables (more on this in lesson #29, Method Types). For example:

    public class Dog {

        private int age; // field variable

        private String type; // field variable

        private String gender = "male"; // field variable (can be defined here)

        public static void main(String[] args) {

            int length = 50; // non-field variable (created inside a method)

            age = 5; // still field variable (created outside main method)

        }

        /* implementation code */

    }

As you can see, field variables can be assigned a value anywhere in the class, they just must be created (declared) outside a method, at the top of the class. Fields can be accessed in instances of the class. For example, the array object has a property called .length. Notice how there are no parenthesis following .length; this means that .length is a field of the array object.

Using the above example of class Dog, you can create a Dog object and print the gender field as follows:

    Dog myDog = new Dog();

    System.out.println(dog.gender); // prints "male"

Now, another very important aspect of classes is the constructor. The constructor has three important rules:

  1. It is called whenever a new instance of a class is created.

  2. It has no return type.

  3. It must have the same name as the class.

The syntax of a constructor, using the above Dog class, is:

    public *CLASSNAME* (*PARAMETERS*) {

        /* implementation code */

    }

As you can see, the constructor does not have a return type. This is because the constructor does not return anything, and its role is to create a new object with specific properties (you can think of this like a void method with a very specific job).

Now, examine the following EmailAccount class. If the constructor had two String parameters (username and password), the constructor would be:

    public class EmailAccount {

        

        // field variables

        private String username;

        private String password;

        // constructor

        public EmailAccount(String usernameInput, String passwordInput) {

            // setting field variables equal to user input

            username = usernameInput;

            password = passwordInput;

        }

    }

In the above code segment, the constructor assigns the field variables username and password to the parameters the user givers when creating a new instance of the EmailAccount class. This allows the user to create multiple different email accounts, each with a different username and password. For example, the syntax for creating a new EmailAccount object is as follows:

There are two parts to this code segment – the variable declaration and variable assignment. Although this code segment may look different, it is essentially like creating any other variable. You can see the similarities and differences between the two variables below:

    int myNumber = 25;

    /* myNumber is type int, myNumber equals 25 */


    EmailAccount myEmail = new EmailAccount("John", “Password1234”);

    /* myEmail is type EmailAccount, myEmail is an EmailAccount object
    with a username of "John" and a password of “Password1234” */

In the above code, new EmailAccount("John", “Password1234”) is when the constructor of the class is called with the parameters of “John” and “Password1234”. The constructor is then used to create a new email account for John with a password of “Password1234”.

Sometimes, there are no parameters when creating a new object – this means that either the constructor has no parameters or the class is using a default constructor, which is a constructor generated by the computer because the programmer did not create a constructor. A default constructor requires no parameters, so if the EmailAccount class had a default constructor, its instance would be declared as follows:

    EmailAccount myEmail = new EmailAccount(); // no parameters

Next, let’s learn how to call methods in other classes. So far, we have only called methods inside the same class they were created. However, in order to call a method from a different class, different syntax is needed. Let’s examine the following code:

    public class Class1 {

        public void printNumber(int num) {

            System.out.println(num);

        }

    }

    public class Class2 {

        public static void main(String[] args) {

            /* your code here */

        }

    }

In this code segment, we have two different classes. Class1 has a method named printNumber which prints an input number to the console. If we want to run printNumber from the main method in Class2, we must first create a Class1 object, shown here:

    Class1 myInstance = new Class1(); // default constructor – no parameters

Now, there are two main types of method calls, static and non-static. The real differences between static and non-static methods will be covered in lesson #29 (Method Types), but for now you simply need to understand the difference in their method calls. Since the printNumber method is non-static, use the following syntax to call the printNumber method:

As you can see, this is the same syntax as the other method call, but now we simply add the object name and a dot in the front. Altogether, the new code would print 26:

    public class Class1 {

        // non-static method

        public void printNumber(int number) {

            System.out.println(number);

        }

    }

    public class Class2 {

        public static void main(String[] args) {

            Class1 myInstance = new Class1(); // instance of Class1

            myInstance.printNumber(26); // non-static method call

        }

    }

However, if the printNumber method was static, then you do not need to create an instance of the class. Instead, the method call uses the class name instead of an instance, as shown here:

    Class1.printNumber(26); // static method call

Overall, classes are very useful to programmers for creating new objects in order to build complex programs. Understanding class structure and syntax is very important to being able to create and use the variety of classes that Java offers.

Lesson Quiz

1. What is an instance of a class?

a. The group of variables that are inside the class.
b. The object of a class which can be used to exhibit the properties and behaviors of that class.
c. The name of the class.
d. The group of methods that are inside the class.

2. Which of the following must be true based on the below code?

    BankAccount myAccount = new BankAccount(); // BankAccount is a class
a. myAccount is a method of the BankAccount class.
b. The above code would produce an error because there are no parameters in the instantiation of the myAccount object.
c. The BankAccount class must contain a constructor with multiple parameters.
d. myAccount is an object that can use the properties and behaviors of the BankAccount class.

3. Based on the below code, if the class BankAccount has the non-static method deposit(String password, double amount), what is the correct syntax used to call that method?

    BankAccount myAccount = new BankAccount(); // BankAccount is a class
a. myAccount.deposit(500, "password");
b. deposit("password", 500);
c. BankAccount.deposit("password", 500);
d. myAccount.deposit("password", 500);

Written by Chris Elliott

Notice any mistakes? Please email us at [email protected] so that we can fix any inaccuracies.