The course is part of this learning path
This training course introduces you to the basic principles of creating Java classes. We’ll review in depth the coding requirements to create a new Java class, detailing things like constructors, fields, methods, instance variables vs static variables, etc.
Learning Objectives
- Be able to code a simple Java class
- Understand instance variables and static variables
- Be able to create object instances
- Understand the differences between Primitives vs Object References
- Be able to Implement the main method to create an instance of the defined class
- Write a class with accessor methods to read and write private instance variables
- Write a constructor to initialize an instance with data
- Write a constructor that calls other constructors of the class to benefit from code reuse
Prerequisites
- A basic understanding of software development
- A basic understanding of the software development life cycle
Intended Audience
- Software Engineers interested in learning Java to develop applications
- Software Architects interested in learning Java to design applications
- Anyone interested in basic Java application development and associated tooling
- Anyone interested in understanding the basics of the Java SDK
- [Instructor] Okay, welcome back. In this lecture, we'll describe the requirements to create a simple Java class. The key objectives of this lecture will be for you to understand the requirements to code a simple Java class, be able to define instance variables for a Java class, be able to create object instances, understand the differences between primitives versus object references, and be able to implement a main method to start program execution. To begin with, let's review what a class is within Java, and like procedural languages, Java forces us into the object-orientated world. Everything in Java exists inside a class definition which is then used to create objects. A program is made up of a collection of dynamically created objects which send messages between each other. All code in Java is implemented within a class. Objects, by definition, are made from classes. A class is composed of fields and methods.
Multiple object instances can be created, or instantiated, from the same class. Object-orientated programming is very different from procedural programming in that a class defines shared behavior, object instances provide unique state, and data can be hidden within the object. So exactly what is a class? A class is a template for building objects. A class encapsulates all of the features of an object, that is, its data elements and its instance methods. When you write a class, you are defining an object's structure and its behavior. An object's structure is determined by its fields while its behavior is determined by its methods. When you create a new object from a class, you are creating an instance of that class. Each instance of a class has its own instance variables and therefore is independent of each and every other object of the same class. Let's now take a closer look at a simple example of a class. For starters, a class must be defined using a class block. All fields and methods are listed within this block. Directly inside the class block are the fields of the class. These define the structure of data as a data record. These fields can be declared as any valid Java type. Also, within the class block are the method blocks. Each method is implemented similarly to functions in other languages. Methods may take arguments and may provide a return value. A special type of method called a constructor can be defined to specify how the object is initialized when it is created. Access modifiers can be applied to class definitions, methods, and fields to specify their visibility. When a class is defined as public, the class definition can be seen by other classes while a class that has been defined without an access modifier can only be seen by other classes within the same package. When defining members of a class, fields, or methods, two additional access modifiers of a class can be added. By defining a field or method as private, the member becomes only visible to the class in which it has been defined while defining it as protected also makes the member visible to subclasses. Instance variables, or otherwise referred to as just fields, hold the state of the object and are visible to all of the methods defined in the same class.
Fields are set to their default values when the object is created or to the value you explicitly initialize them to. Fields define the structure of an object. Fields are typically defined at the start of the class definition. Fields declared as public can be accessed from anywhere, but as you'll soon see later, this is usually undesirable. Instead, a more desirable pattern is to declare the fields private and create public access methods. When you design a class, you typically define the state that objects or instances of the class will manage. For example, the Employee class, as shown here, has three private instance variables, the employee's age and first and last names. Access to each of these three private instance variables is provided through public getter and setter methods. Instances or objects of the Employee class can then go about setting and maintaining their own values. Java provides a few non-object-orientated concepts, the first of which are primitive types. These are very similar to types in a language like C. They hold a value and have no class properties. Java defines eight primitive types: byte, char, boolean, short, int, long, float, and double. These types are predefined and reserved keywords and hold simple and singular values stored on the stack. Understanding primitives versus object references is an important concept within Java. As we've just discussed, a primitive field type holds a value on the stack. On the other hand, Java object references hold the address of the object to which they refer. The type of the reference is the type reference to object where the object is the class it refers to. It is said that Java has no pointers. This is not entirely accurate as these references are pointers. The difference with Java is that pointers are strongly typed, and these references cannot be manipulated in such ways as incrementing the reference values, et cetera. When it comes to creating objects or instances of a class, the new operator must be used. It causes the invocation of a class constructor and returns a reference to that object.
A class constructor is a method with the same name as the class itself. If the constructor requires parameters, then they are passed as method arguments. When we create a new object, the new operator creates the object using a class constructor. Then, it returns a reference to that object. The returned reference is then assigned to the object reference through the use of the assignment operator or equals sign. When an object is no longer referenced, it is said to be eligible for garbage collection by the JVM. In Java, the main method is considered a special method. It allows the class to become a starting point for running an application. The Java interpreter, which is the application that runs our Java code, is executed as an operating system command. We must pass to this command the name of a class to start executing. The class provided must itself contain a main method. It is the well-known method that the Java interpreter will use as an entry point to begin execution. We'll be looking at this method in more detail later in the course. Dot notation is used heavily within Java. The dot operator is used on object references to access fields and methods of that object. Most commonly, it is used to invoke the methods of an object instance. As shown here, fields of the object can also be accessed using the dot operator. The dot is generally referred to as an operator. However, in looking more closely at the Java language specification, it would probably be more accurately defined as a separator. A Java program can quickly be instructed to write messages out to the console. To do so, you can use the System.out.println method where you provide a message as a String parameter to the method. This example illustrates the use of a class name, System, an object reference name, out, and a method call, println. This example takes a String argument and writes it to the standard output stream.
So let's quickly round out our Employee class, and then, we'll instantiate it within a main method of a complete Java application. Here, we see the complete definition of the Employee class with fields to hold its state and a set of getters and setters to manage the state. Next, we provide the complete definition for the MySecondApp class that contains a main method. At runtime, the JVM will know to launch an instance of this class and execute the main method as the starting point for the application. Note, your Java application should have exactly one class that has a main method declared. Declaring more than one main method with the same method signature will cause a compile time error. Before we continue, we should cover off the Java keywords. The Java programming language defines a number of keywords. These keywords are used to define the language constructs and are therefore not allowed to be used as variable names, method names, class names, et cetera. The answers to the above questions are one, objects; two, yes; three, yes, instance fields are automatically initialized when the object instance is created; four, primitive types and object references; five, a main method can be defined to allow the class to be invoked from the command line; six, objects are created from classes using the new operator; and seven, text can be written to standard output using the System.out.println method.
Jeremy is a Content Lead Architect and DevOps SME here at Cloud Academy where he specializes in developing DevOps technical training documentation.
He has a strong background in software engineering, and has been coding with various languages, frameworks, and systems for the past 25+ years. In recent times, Jeremy has been focused on DevOps, Cloud (AWS, Azure, GCP), Security, Kubernetes, and Machine Learning.
Jeremy holds professional certifications for AWS, Azure, GCP, Terraform, Kubernetes (CKA, CKAD, CKS).