Java for Humans {Classes & Objects}

Written by LincolnWDaniel | Published 2015/12/26
Tech Story Tags: programming | java | coding

TLDRvia the TL;DR App

In your life, you’ve learned about many types of animals, people, buildings, sports, schools, and so on. In English class, we refer to these “people, places, or things” as nouns. In Java, we can refer to them as objects — you can think about objects in Java as you do about nouns in English.

Java programs revolve around objects like English sentences revolve around nouns. You can describe a noun with adjectives and you can describe an object with fields, otherwise known as attributes or instance variables. Nouns perform actions with verbs just as objects perform actions with functions, or methods.

As you know, there are three base types, or classes, of nouns — people, places, and things — and from those, you can make infinitely more classes of nouns. Java has a similar idea. There’s a single base class of objects from which we can make infinitely more classes.

In this chapter, you will learn what a class is in Java and how you can make an object from a class.

Why Classes Are Important & Useful

Java is the most widely used object-oriented programming (OOP) language in 2016. OOP is a programming model based on the concept of “objects_”_ which are simply data structures that have fields, or attributes, that hold information (data) about themselves and methods they can perform. The attributes of an object are variables that hold information, or data, about the object while its methods are ways the object can manipulate its data to create new data. This is important because we can use this idea of structured data to write clean, flexible, and maintainable code.

While everything in Java is not an object, most things revolve around objects in Java like the contents of an English sentence revolve around the noun(s) of the sentence. For this reason, it is important for us to know how to create objects and make use of them. This is where classes come in.

A class in Java is simply a template for creating objects with similar attributes and behavior. A Java class can be thought of as a template that defines the attributes and behavior that objects constructed from it can exhibit. With that, we can say an object is merely an instance of a class. From a single class, we can create, or construct, many instances and each instance has the attributes and functionalities that every other instance of the has. Thus, a human is an instance of the Human class, and at the time of publication of this book, there are seven billion instances of the Human class in the world.

Making Objects From Classes

Making a class in Java is easy. There are three key parts of every class but only one is always necessary. A class can have fields, or attributes, methods, or behaviors, and must have at least one constructor. We can create a class that defines the attributes and behavior of humans like this:

public class Human {//TODO: add attributes //TODO: add constructor //TODO: add methods}

We created a simple class called Human. The public keyword at the start of the first line means the class can be accessed from anywhere in your program and the name of the class is in upper camel case. Between the opening curly brace ({) and the closing curly brace (}), we have to define attributes any object, or instance, constructed from this class can have and methods it can perform. Now, before we can create objects from this class, we will need to finish defining it.

Class Fields: Instance Variables

Fields are variables which hold data that describe the attributes of the class and any object constructed from it. Fields that a human would have are its name, age, and height. We add fields to a class by declaring them at the top of the class like this:

public class Human {String name;int age;int height;...}

These fields will hold information about every instance of our Human class, but they do not yet have the information because the class is simply a template. We need to create a constructor which will allow anybody who calls it to pass in the necessary information about the instance of the Human class they are constructing. At the time of constructing an instance of the class, we will assign the given information, values to the instance variables of the instance.

Class Constructor

A class must have a constructor which is used to create a new object from the class each time it is called. Every object created from a class is referred to as an instance of that class. A constructor is simply a method that can be called from different parts of your program to create instances of a defined class.

Although we have not covered methods, yet, it is good to know that methods have return types that tell the caller what datatype to expect back as a result of calling the method. However, some methods don’t return anything at all. We will learn more about return types in the Methods & Dot Notation Chapter.

The constructor has no explicit return type because it’s a factory method, which means it creates a new instance of the class and returns the new instance to the caller. The constructor of a class must have the same name as the class and is case sensitive. Finally, the constructor can accept information from the caller as parameters that will be assigned to the instance fields of the instance being created. We can create a constructor for our Human class that asks the caller to provide the name, age, and the height of the new Human instance like so:

public class Human {... //the constructor of Human public Human(String name,int age, int height){//set this object's name with the provided name this.name = name;//set this object's age with the provided age this.age = age;//set this object's height with the provided height this.height = height;}}

The constructor can be thought of as the doctor who gives birth to your new object and all the doctor asks is that you fill out the birth certificate to describe your new object. The constructor’s parameters says that if anybody wants to create an instance of our Human class, they must provide a name, age, and height for the new Human instance as arguments and it will use that information to initialize the new instance’s instance variables — the name, age, and height fields. Like any other method, we can manipulate data in the constructor aside from assigning the values of our new object’s fields, but it’s good practice to keep the constructor as short as possible. Once the constructor is done creating the new object, it returns it to the caller to be saved to a variable for later use:

public static main(String[] args) {Human newHuman = new Human("Lincoln", 22, 5);}

The keyword this tells the compiler that we are referring to the current instance of the class: if we want to refer to the name field of this new Human object, we say this.name so the compiler doesn’t confuse it with the name parameter that is provided as an argument to the constructor method.

Instance Methods

Remember that nouns perform actions with verbs in sentences and objects in Java programs perform actions by use of their methods. A class defines methods any object constructed from the class can perform. These methods are referred to as instance methods because they can only be performed by an instance of the class. We are all instances of the Human class, so we share functionality, or methods. We speak, run, jump, sleep, walk, wave, work, and so much more. All of these actions are predefined by our human biology and anatomy— our class.

The opening and closing curly braces define a scope_: the opening starts the scope and the closing ends it. Classes and methods, among others, have scope, and the class scope is the highest level scope in a class. While we can start new method scopes in the class scope, we cannot start new method scopes in a method’s scope._

We can add methods to our classes in Java by declaring them between the opening and closing curly braces, or scope, of the class. Let’s add a few methods to our Human class to make our Human objects more functional:

public class Human {... //every instance of a Human can speak public void speak(){System.out.println("Hi! I am " + name + ".");}

_//set the name of the Human object_    **public void** setName(String newName) {  
    **this**.**name** \= newName;  
}  

_//return the age of the Human object_    **public int** getAge() {**return age**;}  

}

We will look at methods in more detail in future chapters so don’t worry about fully understanding the details yet. All that matters right now is that methods allow objects to do things. What we did was, first, add a method that will allow instances of our Human class to speak and introduce themselves. The second method allows our Human objects to change their name when they want. This is often referred to as a setter method because it sets one of an object’s instance variables to a new value and returns nothing — void. The last method allows others to read the age field of a Human instance. This kind of method is referred to as a getter method because it gets and returns one of an object’s instance variables.

Static Fields & Methods

Unlike instance fields and methods, static fields and methods belong to a class and can be accessed without an instance of the class. That means that a class’s factory method is also a static method. In the next chapter, we will learn more about static fields and methods, why they are useful, and when we should make use of them.

Next Chapter

Java for Humans {Static Fields & Methods}_We’ve learned that we can create classes to create objects from and that those objects, or instances of the class, can…_medium.com

Table of Contents

Java for Humans {Table of Contents}_I am writing this book to teach anybody with the slightest bit of interest in computer science, software engineering…_medium.com


Published by HackerNoon on 2015/12/26