Lesson 2 - First object-oriented app in Java - Hello object world
In the previous lesson, Introduction to object-oriented programming in Java, we introduced the object-oriented programming and went over what makes it more efficient than any other programming methodology. We already know that objects have fields and methods. We also know that to create an object we'd have to create a class first. Remember that a class is a pattern according to which we create instances later.
As we did in the Basic constructs of Java course we'll create what must always be done when you encounter a new paradigm in programming, a "Hello World" program. A Hello object world program, to be precise!
We'll start by creating a new Java application as we're used to. In the Projects window, on the left, right-click on the package and select New -> Java Class.
We'll name our class Greeter and confirm. We name classes using CamelCase, meaning that the first letter in every word in the class name is capitalized and we don't write spaces. The name, of course, shouldn't contain any accent characters, if your native language uses any, you can use them in strings, but never in identifiers.
We're going to create a "greeter" object using this class later, which will be able to greet the user. You might've noticed by now that we're treating the program in a different way, for every action, there is some object responsible. One should not simply start by writing stuff into the main() method. In our case, it may seem useless, but in more complex applications it'll prove to be more than worthwhile
Another .java file will be added to our package and NetBeans will open it for us. We can later return to the original HelloObjects.java with the main() method using tabs or via the Projects window.
Let's take a look at what NetBeans has generated for us and add a greeting method to the class.
package helloobjects; public class Greeter { }
As methods are gathered into classes, classes are gathered into packages. To make our class visible in HelloObjects.java, where we have the main() method, we'd have to give them a common package. Our class does it automatically, NetBeans places new classes in the same package that the application is in. Instead of "helloobjects" you'll have your application name there. If you haven't named it manually, it will automatically name it javaapplication1.
In the package, there's our class declared by the class keyword. The class is named Greeter and it's empty.
Notice that the code is almost the same as in HelloObjects.java. We now understand what we looked over in the previous course. Our console program was actually a class containing the main() method, and this class was placed in a package. You see, in Java, there is no real way of creating "non-OOP programs", which is a good thing
Next, we'll add a greet() method to the Greeter class, which will be publicly visible and won't return a value or take any parameters.
In Java, we declare methods as follows:
[Access modifier][return type][methodName]([parameters])
We'll write an access modifier before the method, which in our case is public. To make the method not return a value we must declare the method using the void keyword. Followed by the method's name, which we will write in camelCase as we do with variables (the first letter is lower case). Parentheses with parameters are required, we'll leave them empty since the method won't have any parameters. In the method body, we'll write code that prints a message to the console.
Our class will now look like this:
public class Greeter { public void greet() { System.out.println("Hello object world!"); } }
That's all we'll do for the class for now. Let's move on to HelloObjects.java.
We'll create an instance of the Greeter class in the main() method body. Which will be a greeter object that we'll be able to work with. We store objects in variables and use the class name as the data type. Instances usually have the same name as classes, but with the first character in lowercase. Let's declare the variable and then store a new Greeter class instance within it:
Greeter greeter;
greeter = new Greeter();
The first line says: "I want a variable named "greeter" that will later contain a Greeter instance". We've already worked with the variables like this.
The second line contains the new keyword which will create a new Greeter class instance. We assign this instance to our variable.
When a new instance is created, the constructor is called. The constructor is a special class method, that's why we write the empty parentheses when creating an instance, we're calling this "creation" method. The constructor usually contains some initialization of the object's internal state, e.g. it initializes the fields with default values. We haven't declared a constructor in our class, that's why Java created the implicit parameterless constructor. So creating an instance of an object is similar to calling a method. Of course, the entire code can be shortened to:
Greeter greeter = new Greeter();
Since now we have a Greeter class instance in a variable, we can let it greet
the user. We'll call the greet() method as
greeter.greet()
. The main() method code will now look like
this:
{JAVA_OOP}
public class Greeter {
public void greet() {
System.out.println("Hello object world!");
}
}
{JAVA_MAIN_BLOCK}
Greeter greeter = new Greeter();
greeter.greet();
{/JAVA_MAIN_BLOCK}
{/JAVA_OOP}
Let's run the program:
Your first OOP app
Hello object world!
You can run the program in our online compiler as well, just notice that all classes are in the same file there if you click on the code. It's simpler for our online samples, however, you keep classes in separated files in your projects. We have successfully made our first object-oriented app!
Now let's add a name parameter to our greet() method, so it could greet the user properly:
public void greet(String name) { System.out.println("Hi " + name); }
The syntax of the method parameter is the same as the syntax of a variable. If we wanted more parameters, we'd separate them with commas. Let's modify our main() method now:
{JAVA_OOP}
public class Greeter {
public void greet(String name) {
System.out.println("Hi " + name);
}
}
{JAVA_MAIN_BLOCK}
Greeter greeter = new Greeter();
greeter.greet("Carl");
greeter.greet("Peter");
{/JAVA_MAIN_BLOCK}
{/JAVA_OOP}
Our code is now in a method and we're able to call it multiple times with
different parameters. We don't have to copy "Hi ..."
twice. We'll
separate our code logically into methods from now.
Console application
Hi Carl
Hi Peter
Let's add some field (attribute) to the class, e.g. a text where the greeting will be stored. We declare fields as variables as well. We will also write an access modifier before them just like before otherwise Java would assume that they're package-private (see further in the course). Here's what your class should look like at this point:
public class Greeter { public String text; public void greet(String name) { System.out.println(text + " " + name); } }
We have to initialize the text in the instance created in HelloObjects.java:
{JAVA_OOP}
public class Greeter {
public String text;
public void greet(String name) {
System.out.println(text + " " + name);
}
}
{JAVA_MAIN_BLOCK}
Greeter greeter = new Greeter();
greeter.text = "Hi";
greeter.greet("Carl");
greeter.greet("Peter");
greeter.text = "Hello programmer";
greeter.greet("Richard");
{/JAVA_MAIN_BLOCK}
{/JAVA_OOP}
Console application
Hi Carl
Hi Peter
Hello programmer Richard
In object-oriented design, it's not recommended to let each object control
the input and output, i.e. printing lots of stuff into the console. Each object
should have a single responsibility and shouldn't exceed its purpose. Let's make
our object solely responsible for creating the greeting text, and we'll move the
printing outside the object, i.e. to the main()
method. The
advantage to designing objects with a single responsibility is that they're then
universal and reusable. Our object can only print text to the console now, but
we'll change it so the method will only return the text and it'll be up to the
recipient to decide what to do with it. Like this we could store greetings into
files, print them on websites or process them further.
Since we want the method to return a string value, we'll change it from being a void type to a String type method. We use the return keyword to return a value. The return keyword terminates the method and returns the value. Any code in the method's body after the return will not be executed! Let's modify both classes:
The greet() method in Greeter.java:
public String greet(String name) { return text + " " + name; }
The main() method body in HelloObjects.java:
{JAVA_OOP}
public class Greeter {
public String text;
public String greet(String name) {
return text + " " + name;
}
}
{JAVA_MAIN_BLOCK}
Greeter greeter = new Greeter();
greeter.text = "Hi";
System.out.println(greeter.greet("Carl"));
System.out.println(greeter.greet("Peter"));
greeter.text = "Hello programmer";
System.out.println(greeter.greet("Richard"));
{/JAVA_MAIN_BLOCK}
{/JAVA_OOP}
Now, our code follows the guidelines of good OOP and over all programming practices. We will also add comments in our class accordingly. We'll add comments over the class name and over the name of each field and method. We'll use the Javadoc comments, /** Comments */, where we'll describe everything that's happening. Comments are useful when we make new class methods because its description will then be available to us in NetBeans. A fully documented class might look something like this:
/** A class represents a greeter whose purpose is to greet the user */ public class Greeter { /** Greeting text */ public String text; /** * Greets the user with the stored greeting and his/her name * @param name The user's name * @return The greeting text */ public String greet(String name) { return text + " " + name; } }
Let's check and see if NetBeans actually displays descriptions we've set in Javadoc:
Great! Our program already has some quality to it, despite it being relatively useless. If you want, you can try to create an object-oriented remake of our console calculator. In the next lesson, Solved tasks for OOP in Java lesson 1-2, we'll program a simple game. We'll make two objects, warriors, compete in an arena, which will also be an object. See? Now you have something to look forward to!
In the following exercise, Solved tasks for OOP in Java lesson 1-2, we're gonna practice our knowledge from previous lessons.