Never confuse education with intelligence, you can have a PhD and still be an idiot.
- Richard Feynman -



Difference between revisions of "Chapter:Classes I"

From Juneday education
Jump to: navigation, search
(Comments and documentation)
m (Class declaration)
 
(42 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 +
=THIS PAGE IS REPLACED BY:=
 +
* [[Chapter:Classes_-_Introduction]]
 +
* [[Chapter:Classes_-_Introduction_-_Exercises]]
 +
* [[Chapter:Classes_-_Declaration]]
 +
* [[Chapter:Classes_-_Declaration_-_Exercises]]
 +
* [[Chapter:Classes_-_Packages]]
 +
* [[Chapter:Classes_-_Packages_-_Exercises]]
 +
* [[Chapter:Classes_-_main]]
 +
* [[Chapter:Classes_-_main_-_Exercises]]
 +
* [[Chapter:Classes_-_Commenting_code]]
 +
* [[Chapter:Classes_-_Commenting_code_-_Exercises]]
 +
 
=Meta information about this chapter=
 
=Meta information about this chapter=
 
<div class="mw-collapsible mw-collapsed">
 
<div class="mw-collapsible mw-collapsed">
Line 74: Line 86:
 
</div>
 
</div>
 
</div>
 
</div>
 
==NOTE TO THE TRANSLATORS==
 
We are working on assignment 2 and have paused the writing of this chapter. This chapter will contain the following parts:
 
 
* Short reflection on what are classes for?
 
** starting point (simple class with only main)
 
** (data)type for objects (grouping state and functionality - where functionality is the public interface to the objects)
 
*** domain objects (Player, File, Movie, Book, Document)
 
*** functional component objects (GameEngine, Logger, ClassLoader, DatabaseConnection etc)
 
** function library (like java.lang.Math with only static methods - not very common or typical for OO systems)
 
* What are the parts of a compilation unit (source code file) with a class declaration (as per the scope of this book!)
 
** package declaration
 
** import declarations
 
** class declaration
 
** variable declarations
 
*** instance variables
 
*** class variables
 
** constructor declarations
 
*** default constructor inserted by the compiler (no arguments)
 
*** a single constructor
 
*** overloaded constructors
 
** method declarations
 
*** instance methods
 
*** class methods
 
* Access modifiers (a closer look at private and public) (default and protected deferred to a more advance book)
 
** public - the meaning of
 
** private - the meaning of
 
* Other modifiers
 
** static, the meaning of
 
** final (variable context for constants - final classes and methods deferred to later chapters)
 
** list of other modifiers for completeness but not explained in the scope of this book (volatile, transient, synchronized, abstract)
 
* Comments in the source code - syntax rules
 
** single line comment <code>//</code>
 
** multiple line comment <code>/* bla */</code>
 
** javadoc comment (syntax and purpose, not hands on using it) - they should be able to read and recognize and understand the purpose
 
* Other keywords
 
** this
 
** for completeness - extends (deferred to inheritance) implements (deferred to interfaces)
 
** list of all java keywords - well documented which ones are relevant in the scope of this book
 
* Annotations (we'll mention it but will only show @Overrides and not until the inheritance chapter)
 
* Naming conventions (naming packages, classes, methods, variables, constants)
 
 
We will make sure that assignment 2 contains most of the concepts from this chapter, but more importantly (and consequently that all parts of the assignment 2, has been taught (including exercises) in this chapter (if they relate to the concept of Java classes).
 
 
This way, we make sure that the assignment 2 really wraps it all up, and that the students have been given the chance to practice every challenging part of the assignment. Together with the remaining chapters (inheritance, interfaces and exceptions) the assignment 2 will cover every aspect of the bulk of this book. Assignment 3 will be a continuation of assignment 2, adding features (and maybe comments).
 
 
Note that every section below this one is subject to change or deletion!!! STOP READING HERE! <code>;-)</code>
 
  
 
==Chapter Videos==
 
==Chapter Videos==
* What is a clas? And why do we need to know about it?
+
* Classes I [https://vimeo.com/channels/1128844 (English)] [https://vimeo.com/channels/1128843 (Swedish)]
* TODO: create presentation and video for "Class declarations" (source code layout in general - what can a class contain?)
+
* TODO: create presentation and video for "package declaration"
+
* TODO: create presentation and video for "Import statements"
+
* TODO: create presentation and video for "Variables - instance, static, constants"
+
* TODO: create presentation and video for "Constructor declaration and use"
+
* TODO: create presentation and video for "Method declarations and use (instance, static)
+
* TODO: create presentation and video for "Access modifiers"
+
* TODO: create presentation and video for "Other modifiers"
+
* TODO: create presentation and video for "Comments"
+
* TODO: create presentation and video for "Other keywords"
+
* TODO: create presentation and video for "Naming conventions"
+
* TODO: create presentation and video for
+
 
See below for individual links to the videos.
 
See below for individual links to the videos.
  
 
==Description==
 
==Description==
About classes...
 
* Source code layout for class
 
** package decl
 
** import statments
 
** class decl
 
** variables (static, instance)
 
** constructor(s)
 
** methods (static, instance)
 
* Access modifiers
 
** default (package private)
 
** private
 
** protected (for completion, we will not use it during this course)
 
** public
 
* Other modifiers
 
** static (variable, method, even class - more about that later, initializer block (more about that later))
 
** final (variables, class (more later), method (more later)
 
** abstract (just a teaser for coming chapters)
 
** There are a few more modifiers we won't use in this course: transient, volatile, synchronized, native
 
* Comments (three types)
 
** Single line
 
** multiple line
 
** javadoc style
 
* other keywords related to classes
 
** The this keyword (will be used for instance in constructors)
 
** extends (more on that in later chapters)
 
** implements (more on that in later chapters)
 
* Naming conventions
 
** Class names
 
** variable names
 
** constants' names (final variables)
 
** method names
 
** constructor "names" - same as class - is it a name or a type? ;-)
 
** package names
 
  
 
==Class declaration==
 
==Class declaration==
 
In the previous chapter we introduced objects and classes so we should all have a basic idea of what objects and classes are.
 
In the previous chapter we introduced objects and classes so we should all have a basic idea of what objects and classes are.
  
This section deals with the components of a class and the source code layout for a class declaration. What parts constitutes a class? Before we answer that, we start by looking at what are the parts of a class as defined in a source code file. A Java class definition in a source code file ''can'' contain the following elements:
+
The chapters on classes deals with the components of a class and the source code layout for a class declaration. What parts constitutes a class? Before we answer that, we start by looking at what are the parts of a class as defined in a source code file. A Java class definition in a source code file ''can'' contain the following elements:
 
* A package declaration - declares logical association expressed as a package (which corresponds to the path to the class file)
 
* A package declaration - declares logical association expressed as a package (which corresponds to the path to the class file)
 
* import statements (if needed)
 
* import statements (if needed)
 
* The actual class declaration with the class name and the start of the block of code for the class
 
* The actual class declaration with the class name and the start of the block of code for the class
 
* The variables needed to keep the state of objects created from this class (instance variables)
 
* The variables needed to keep the state of objects created from this class (instance variables)
* The variables common to all instances created from this class (static variables)
+
* The variables common (shared, will exist in only one copy) to all instances created from this class (static variables)
 
* The constructor(s) providing means to create instances from this class
 
* The constructor(s) providing means to create instances from this class
 
* The methods of instances of this class - what objects of this class can do
 
* The methods of instances of this class - what objects of this class can do
Line 188: Line 108:
 
* Initializers - you can actually put blocks of code directly in the class body - this is outside of the scope for this book
 
* Initializers - you can actually put blocks of code directly in the class body - this is outside of the scope for this book
  
We'll discuss these components one by one, in the subsections below. Note that the last two components are only included here in order for us to be more complete. We don't want to hide these components for you, but we will not go into any details about the use of them in the scope of this book.
+
We'll discuss these components one by one, in the chapters on Classes. Note that the last two components are only included here in order for us to be more complete. We don't want to hide these components for you, but we will not go into any details about the use of them in the scope of this book.
 
+
 
+
  
 
==Package declaration==
 
==Package declaration==
 +
===Video===
 +
* Classes I - Packages [https://vimeo.com/182101406 (English)] [https://vimeo.com/182101407 (Swedish)] ([[:Media:Class_declaration.pdf|pdf]])
  
 
=== Description ===
 
=== Description ===
Line 284: Line 204:
 
</source>
 
</source>
  
You should remain in the directory signified by "." in above. Download the [https://raw.githubusercontent.com/progund/classes-package-decl/master/Game.java Game.java] source code into <code>src/org/progund</code> (when we say "download a file into a directory", we actually mean that you should download a file and make sure you move it to that directory). Open the file and look at the package declaration. Remember that if there is a package declaration, it must be on the first line of the source code file.
+
You should remain in the directory signified by "." in above. Download the [https://raw.githubusercontent.com/progund/classes/master/classes-package-decl/Game.java Game.java] source code into <code>src/org/progund</code> (when we say "download a file into a directory", we actually mean that you should download a file and make sure you move it to that directory). Open the file and look at the package declaration. Remember that if there is a package declaration, it must be on the first line of the source code file.
  
 
# What is the package name?
 
# What is the package name?
Line 350: Line 270:
 
#: The class should have no main method.
 
#: The class should have no main method.
 
# Compile and execute the class. Did it work? Why?
 
# Compile and execute the class. Did it work? Why?
# Add a main method to the class. The main method could simply output the class' name, using println. The code look something like this:
+
# Add a main method to the class. The main method could simply output the class' name, using println. The code looks something like this:
 
#:<source lang="Java">
 
#:<source lang="Java">
 
   public static void main(String[] args) {
 
   public static void main(String[] args) {
Line 369: Line 289:
 
# Execute the Game class (the first class you wrote). Did it work? Why?
 
# Execute the Game class (the first class you wrote). Did it work? Why?
 
# Change the name of the method <code>main</code> to <code>maine</code> in the Game class. Compile and execute. Did it work? Why?
 
# Change the name of the method <code>main</code> to <code>maine</code> in the Game class. Compile and execute. Did it work? Why?
# Change the name of the access modifier <code>public</code> to <code>private</code> in the Game class. Compile and execute. Did it work? Why?
+
# Change the name of the method back to main. Change the main methods's access modifier <code>public</code> to <code>private</code> in the Game class. Compile and execute. Did it work? Why?
 
# Make the main method, in the Game class, public again. Compile and execute. Did it work? Why?
 
# Make the main method, in the Game class, public again. Compile and execute. Did it work? Why?
# In the main method of the Gamer class we want to invoke the <code>maine</code> method in the Game class. You can do it like this:
+
# Ok, one more time. Let's rename the method <code>main</code> to <code>maine</code> in the Game class. In the main method of the Gamer class we want to invoke the <code>maine</code> method in the Game class. You can do it like this:
 
#:<source lang="Java">  
 
#:<source lang="Java">  
 
package org.gamefactory.textgame;
 
package org.gamefactory.textgame;
Line 378: Line 298:
  
 
   public static void main(String[] args) {
 
   public static void main(String[] args) {
       org.gamefactory.textgame.Game.maine(null);
+
       Game.maine(null); // using a class in the same package works without import!
 
       System.out.println("Gamer");
 
       System.out.println("Gamer");
 
   }
 
   }
Line 386: Line 306:
 
# Change the name of the <code>maine</code> back to <code>main</code>. Compile both classes and execute the Gamer class. Did it work? Why?
 
# Change the name of the <code>maine</code> back to <code>main</code>. Compile both classes and execute the Gamer class. Did it work? Why?
  
===Solutions to Starting pint of a program ===
+
===Solutions to Starting point of a program ===
 
<div class="mw-collapsible mw-collapsed">
 
<div class="mw-collapsible mw-collapsed">
 
Expand using link to the right to see the full content.
 
Expand using link to the right to see the full content.
Line 412: Line 332:
 
}
 
}
 
</source>
 
</source>
#: It both compiles and executes. It can be executed since it has a valid main method.
+
# It both compiles and executes. It can be executed since it has a valid main method.
 
# The class could look something like this:
 
# The class could look something like this:
 
#:<source lang="Java">
 
#:<source lang="Java">
Line 433: Line 353:
 
}
 
}
 
</source>
 
</source>
# It both compiles and executes. It can be executed since it has a valid main method.
+
#It both compiles and executes. It can be executed since it has a valid main method.
# It worked now as it worked before. Nothing has changed so why shouldn't it work.
+
#It worked now as it worked before. Nothing has changed so why shouldn't it work.
 
# Changing the name to <code>maine</code> does not satisfy the requirements Java sets on a main method so, although the class compiles fine, the class can't be executed.
 
# Changing the name to <code>maine</code> does not satisfy the requirements Java sets on a main method so, although the class compiles fine, the class can't be executed.
 
# Changing the access modifier to <code>private</code> does not satisfy the requirements Java sets on a main method so, although the class compiles fine, the class can't be executed.
 
# Changing the access modifier to <code>private</code> does not satisfy the requirements Java sets on a main method so, although the class compiles fine, the class can't be executed.
 
# Now it compiles and can be executed again, since the class is valid Java and the main method satisfies the requirements.
 
# Now it compiles and can be executed again, since the class is valid Java and the main method satisfies the requirements.
# The Game and Gamer classes compiles. Game class executes fine. We can see that the Game class can invoke the <code>maine</code> method in the Game class.
+
# The Game and Gamer classes compile. Game class executes fine. We can see that the Gamer class can invoke the <code>maine</code> method in the Game class.
# The Game and Gamer classes compiles. Game class executes fine. We can see that the Game class can invoke the <code>main</code> method in the Game class. We can see that there's no magic in the main method. The only thing that makes it differ from other method is that Java can start it - which is kind of nice :)
+
# The Game class compiles and executes fine. The Gamer class will not compile since it invokes a method (<code>maine</code>) that does not exist (any more) in the Game class.
  
  
Line 447: Line 367:
 
== Comments and documentation ==
 
== Comments and documentation ==
  
Imagine going back to classes you wrote some years ago. Or image reading someone else classes. It is sometimes hard to understand what the class does, or at least intends to do. Java provides an easy way to write comments, not code and not compiled. There are two ways to write comments in your code.
+
Imagine going back to classes you wrote some years ago. Or image reading someone else's classes. It is sometimes hard to understand what the class does, or at least intends to do. Java provides an easy way to write comments, which is text not considered as code and therefore ignored by the compiler. There are two ways to write comments in your code.
  
There is a format way you can use when writing comments with which you can create manuals for classes and packages. See below on Javadoc.
+
There is a format way you can use when writing comments with which you can create manuals for classes and packages. See [[Javadoc]].
  
 
==== single line ====
 
==== single line ====
Line 519: Line 439:
 
=== Exercises ===
 
=== Exercises ===
  
# Create a file like the one below (note that the file is in a package and you need to crate (and use) a corresponding directory structure)).  
+
# Create a file like the one below (note that the file is in a package and you need to crate (and use) a corresponding directory structure).  
 
#:<source lang="Java">  
 
#:<source lang="Java">  
 
package org.commenteers;
 
package org.commenteers;
Line 536: Line 456:
 
</source>
 
</source>
 
# Write a comment before the main method saying "This is the main method".  
 
# Write a comment before the main method saying "This is the main method".  
# Change the class so that the first println statement is not done. Use single line comment to achieve this.
+
# Change the class so that the first println statement is ignored by the compiler. Use single line comment to achieve this.
 
# Write an introduction text to the class using multi line comments.
 
# Write an introduction text to the class using multi line comments.
 
# Change the class so that the for loop is not executed (enclose it in a multi line comment)
 
# Change the class so that the for loop is not executed (enclose it in a multi line comment)
 
  
 
===Solutions to - Comments and documentation ===
 
===Solutions to - Comments and documentation ===
Line 546: Line 465:
 
<div class="mw-collapsible-content">
 
<div class="mw-collapsible-content">
  
 +
# Just create it in the correct directory structure!
 
#Suggestion:
 
#Suggestion:
 
#: <source lang="Java">  
 
#: <source lang="Java">  
Line 628: Line 548:
 
</div>
 
</div>
 
</div>
 
</div>
 
==Declaring variables==
 
====Description====
 
If we want to develop a system to manage Passports in a country we divide the system into smaller parts, sub systems. One of these sub systems could be an abstraction of Passport. Each individual passport need to hold information, in some way, about the person for which the Passport is made for. The information could be birth date, height, color of hair etc. To store this kind of information in an object (a Passport instance) we need to have variables int the objects. These variables have values specific to each object, if one person is 190 cm long another person may not be.
 
 
Variables declared inside a class generally serve two purposes. The most common purpose is that instances of the class (objects created from the class, that is object whose type is the class) must have a way to save their state. A class can be seen as a complex type describing a group of similar objects (such as for instance files) and the operations these objects can perform. A file object, for instance, can have an absolute path and a name. This is true for all files (they all have names etc). So the class can be used to describe common treats for these objects. The name is stored in a variable, and since we want to allow for many instances of files to have different names, this type of variable is called "instance variable".
 
 
So, instance variables exist to allow many objects to have different values (state) for a common treat. The other type of variable which can be declared in the class block, is "class variable" (also known as "static" variables). These variables exist to store information about the type (or class) itself, which is the same for all instances. For instance, elaborating on the File class, all file objects in a file system use the same character as "file separator" (on our systems it is <code>/</code> ). There is no point in storing this common value in the memory space of every object we create (since it is the same value for all objects, and it will probably not change). Using the keyword <code>static</code> we can declare a variable in a class which has these characteristics: It will only be stored in one place when the program is running, and it is not specific to any particular one object. In fact, static variables are available even before any object of a class has been created.
 
 
A file class could declare variable like this (leaving out the rest of the class declaration and focusing only on the variables):
 
 
TO BE CONTINUED
 
 
====Videos====
 
====Exercises on variable declaration====
 
We're going to start with creating a class, Member, to use in a system developed to administer members in an organisation. The organisation could be anything from a sport club to a car pool organisation.
 
 
We need to keep track of the members in the organistation. To do this we need the class Member which we're going to use as an abstraction of the actual (physical) members. Each physical member will have a corresponding Member instance (an object) in our system. We don't have knowledge yet on how to store many things of one kind in a good way, but that doesn't matter since the focus right now is to discuss and develop the Member class, so let's begin.
 
 
# Create a class, <code>Member</code> in the package <code>net.supermegacorp.orgmanager</code>. ''Putting your class in a package also means you have to have a corresponding directory structure. So your file <code>Member</code>  should be located in the directory structure like this <code>net/supermegacorp/orgmanager</code> ''
 
# Create a test class <code>MemberTest</code>, with a <code>main method</code>. You should use the package name in the package <code>net.supermegacorp.orgmanager.test</code>. In the main method you should create a <code>Member</code> instance.
 
# Compile and run the code. Don't expect anything to happen.
 
# Output, using <code>println</code>, the instance/object
 
# Compile and run the code. You should see a printout that contains your class name <code>Member</code> followed by <code>@</code> and some digits. We will look at how this printout will change through this lecture and in the coming lecture about inheritance we will reveal how the printout is done. What we can tell you right now is that there is no magic or philosophy behind this.
 
# Add, to the <code>Member</code> class, a instance variable, <code>name</code> with the type <code>String</code>. Make sure to use the <code>public</code> keyword. The keyword public makes it possible for everyone to read/write the variable.
 
# Compile and run the test class again. Nothing should have changed from above.
 
# To the test class' main method you should output the <code>name</code> variable of the <code>Member</code> instance.
 
# Compile and run the test class again. What value of name was printed?
 
# Set the value of the name variable in the object to "Ada"
 
# Compile and run the test class again. What value of name was printed?
 
# Remove the code that outputted the value of name
 
# Now, we will ask you to just do as we tell you. You will get a nice result and in the coming lecture on Inheritance you will get an explanation on what's going on. Add the following code to your <code>Member</code> class' definition:
 
#:<syntaxhighlight lang="Java" line="1">
 
    public String toString() {
 
      return name;
 
    }
 
</syntaxhighlight>
 
# Compile your code and run the test class again. What happened to the initial output of the Member object?
 
# Now add another instance variable, <code>email</code>, also of the type <code>String</code>
 
# Compile your code and run the test class again. What happened to the output of the Member object?
 
# Change the <code>toString</code> method in the <code>Member</code> class to look something like:
 
#:<syntaxhighlight lang="Java"  line="1">
 
    public String toString() {
 
      return name + " " + email;
 
    }
 
</syntaxhighlight>
 
# Compile your code and run the test class again. What happened to the output of the Member object?
 
# In your main method, change the value of the email address to "ada@lovelace.net"
 
# Compile your code and run the test class again. What happened to the output of the Member object?
 
We now have a class Member that can be used in our Member management system. Objects creating from that class will have two instance variables, name and email. This means we (potentially) could continue writing our system. But to write such a system we need more knowledge, so in this course we will do a thing similar to the Member class, to continue practicing on the newly learnt concepts.
 
 
We will continue practicing by developing a class for a system for the police to keep track of the passport of a country's citizens.
 
 
 
An interesting difference between a Member and a passport is that in the former case, the Member, it feels natural to be able to update variables in an object. If you for example a Member change email address it is still the same member.
 
 
If we, on the other hand, want to update a passport, let's say we need to change the birth date of a person (to which the passport belongs) we'll need to create a new physical passport (not an updated).
 
 
Should this be reflected in the code of the class? This is a question we (the authors) would love to spend more time on but right now we don't have the tools so we (the authors) will skip it.
 
 
<ol start="22">
 
<li>
 
Create a class, <code>Passport</code> in a package called <code>org.police.passportsystem</code> The class should have a public <code>String</code> variable, <code>name</code>, to represent the person's (to which the passport belongs) name and a <code>String</code> variable, <code>birth</code>, which represents the birth date of the person.
 
 
''Note: it is a good practice to use specialised classes to store dates, such as the Calendar class. We don't do this at the moment since we want you to be able to feel familiar. We also want you to see later on that the choice of String is not the best approach. Some authors or lecturers use Strings even when storing dates in a database. This is wrong for may reasons, the most obvious being that we can't trust the data in our database doing so. We aim at making you aware of the danger of doing so and give you an alternative solution.''
 
</li>
 
Write a test class, <code>PassportTest</code> in the package <code>org.police.passportsystem.test</code>,  that creates a Passport instance and sets the name of the Passport to "Adam" and the birth date to "1994-01-01".
 
<li>
 
Now, compile both classes.
 
</li>
 
<li>
 
It is "rather" unlikely, actually it would not make sense at all, that we need to change the name or birth date of a person, so we suggest that you change these two variables to be private instead. Compile the class Passport (only that class).
 
</li>
 
<li>
 
Now, compile the PassportTest class as well. Will it work?
 
</li>
 
</ol>
 
 
Not being able to assign or read values from an object makes the keyword private useless, doesn't it? On the contrary. We recommend setting as many variables as possible as private. How to set them then? One way would be a method many authors and teachers like called [[Getters and Setters]]. We do not recommend this at all - at least not in the way it is most commonly taught. Instead we recommend setting the values in a constructor, which is, by pure coincident, the subject of the next section.
 
 
====Solutions to variable declaration====
 
<div class="mw-collapsible mw-collapsed">
 
Expand using link to the right to see the full content.
 
<div class="mw-collapsible-content">
 
# Since the class name should be <code>Member</code> the following code must be stored in a file called Member.java. The content can be:
 
#:<syntaxhighlight lang="Java" line="1">
 
package net.supermegacorp.orgmanager;
 
 
public class Member {
 
 
}
 
</syntaxhighlight>
 
# Since the class name should be </code>Member</code> the following code must be stored in a file called Member.java. The content can be:
 
#:<syntaxhighlight lang="Java" line="1">
 
package net.supermegacorp.orgmanager.test;
 
 
import net.supermegacorp.orgmanager.Member;
 
 
public class MemberTest {
 
 
    public static void main(String[] args) {
 
 
        Member m = new Member();
 
    }
 
 
}
 
</syntaxhighlight>
 
# To compile: <code>javac net/supermegacorp/orgmanager/Member.java net/supermegacorp/orgmanager/test/MemberTest.java</code>
 
#: To execute: <code>java net.supermegacorp.orgmanager.test.MemberTest</code>
 
#: If you want to do the above on one line and execute only if compilation succeeds: <code>javac net/supermegacorp/orgmanager/Member.java net/supermegacorp/orgmanager/test/MemberTest.java && java net.supermegacorp.orgmanager.test.MemberTest</code>
 
# Add a normal println with the object as argument.
 
#:<syntaxhighlight lang="Java" line="1">
 
package net.supermegacorp.orgmanager.test;
 
 
import net.supermegacorp.orgmanager.Member;
 
 
public class MemberTest {
 
 
    public static void main(String[] args) {
 
 
        Member m = new Member();
 
        System.out.println(m);
 
 
    }
 
 
}
 
</syntaxhighlight>
 
# The printout looks like this:
 
#: <code>net.supermegacorp.orgmanager.Member@717da562</code>
 
# Add the String declaration in the class scope, like this:
 
#:<syntaxhighlight lang="Java" line="1">
 
package net.supermegacorp.orgmanager;
 
 
public class Member {
 
 
    public String name;
 
 
}
 
</syntaxhighlight>
 
# To compile: <code>javac net/supermegacorp/orgmanager/Member.java net/supermegacorp/orgmanager/test/MemberTest.java</code>
 
#: To execute: <code>java net.supermegacorp.orgmanager.test.MemberTest</code>
 
#: .. and no changes in the printout.
 
# To access the name variable in an object we use the <code>.</code> like this <code>m.name</code>. Printing it out will make the main code look like this:
 
#:<syntaxhighlight lang="Java" line="1">
 
    public static void main(String[] args) {
 
 
        Member m = new Member();
 
        System.out.println(m);
 
        System.out.println(m.name);
 
 
    }
 
</syntaxhighlight>
 
# <code>null</code> can be seen on the screen. Since we have not assigned a value to <code>name</code> the default value (<code>null</code>) is still in use. When printing a reference with the value <code>null</code>, java simply outputs null.
 
# An example of how this can be done:
 
#:<syntaxhighlight lang="Java" line="1">
 
    public static void main(String[] args) {
 
 
        Member m = new Member();
 
        m.name = "Ada";
 
        System.out.println(m);
 
        System.out.println(m.name);
 
 
    }
 
</syntaxhighlight>
 
# Not so surprisingly "Ada" was printed.
 
# An example of how this can be done is to turn the code into a comment:
 
#:<syntaxhighlight lang="Java" line="1">
 
    public static void main(String[] args) {
 
 
        Member m = new Member();
 
        m.name = "Ada";
 
        System.out.println(m);
 
        //System.out.println(m.name);
 
 
    }
 
</syntaxhighlight>
 
# The class now looks like this 
 
#:<syntaxhighlight lang="Java" line="1">
 
package net.supermegacorp.orgmanager;
 
 
public class Member {
 
 
    public String name;
 
 
    public String toString() {
 
        return name;
 
    }
 
 
}
 
</syntaxhighlight>
 
# The output now looks like this: <code>Ada</code>
 
#: Note that the same output before was <code>net.supermegacorp.orgmanager.Member@717da562</code>
 
#: With the method <code>toString</code> an object defines its own String representation.
 
#: '''Note that <code>toString</code> does not print anything. It returns a string.'''
 
# The class now looks like this 
 
#:<syntaxhighlight lang="Java" line="1">
 
package net.supermegacorp.orgmanager;
 
 
public class Member {
 
 
    public String name;
 
    public String email;
 
 
    public String toString() {
 
        return name;
 
    }
 
 
}
 
</syntaxhighlight>
 
# The output now looks like this: <code>Ada</code>. The value of email is not part of the String returned by the <code>toString</code> method.
 
# The Member class now looks like this:
 
#:<syntaxhighlight lang="Java" line="1">
 
package net.supermegacorp.orgmanager;
 
 
public class Member {
 
 
    public String name;
 
    public String email;
 
 
    public String toString() {
 
        return name + " " + email;
 
    }
 
 
}
 
</syntaxhighlight>
 
# The output now looks like this: <code>Ada null</code>. Since the variable email has not been assigned a value, the default value null is still assigned and thus printed.
 
# The MemberTest code now looks like:
 
#:<syntaxhighlight lang="Java" line="1">
 
package net.supermegacorp.orgmanager.test;
 
 
import net.supermegacorp.orgmanager.Member;
 
 
public class MemberTest {
 
 
    public static void main(String[] args) {
 
 
        Member m = new Member();
 
        m.name = "Ada";
 
        m.email = "ada@lovelace.net";
 
        System.out.println(m);
 
        //System.out.println(m.name);                                         
 
 
    }
 
 
}
 
</syntaxhighlight>
 
# The output now looks like this: <code>Ada ada@lovelace.net</code>. Since the variable email has been assigned the value "ada@lovelace.net" which is printed alongside the value of name.
 
# The passport class will look something like this:
 
#:<syntaxhighlight lang="Java" line="1">
 
package org.police.passportsystem;
 
 
public class Passport {
 
 
    public String name;
 
    public Date  birth;
 
 
}
 
</syntaxhighlight>
 
# The PassportTest class will look something like
 
#:<syntaxhighlight lang="Java" line="1">
 
package org.police.passportsystem;
 
package org.police.passportsystem.test;
 
 
import org.police.passportsystem.Passport;
 
 
public class PassportTest {
 
 
    public static void main(String [] args) {
 
 
        Passport p = new Passport();
 
 
p.name  = "Adam";
 
p.birth = "1994-01-01";
 
 
    }
 
 
}
 
</syntaxhighlight>
 
# Compile and execute like this: <code>javac org/police/passportsystem/Passport.java org/police/passportsystem/test/PassportTest.java  && java org.police.passportsystem.test.PassportTest</code>
 
# The Passport class will now look something like
 
#:<syntaxhighlight lang="Java" line="1">
 
package org.police.passportsystem;
 
 
public class Passport {
 
 
    private String  name;
 
    private String  birth;
 
 
}
 
</syntaxhighlight>
 
#: Compilation of the Passport class (<code>javac org/police/passportsystem/Passport.java</code>) succeeds.
 
# Compilation of the PassportTest class (<code>javac org/police/passportsystem/test/PassportTest.java</code>) fails with the following message:
 
#:<syntaxhighlight lang="Bash" line="1">
 
org/police/passportsystem/test/PassportTest.java:12: error: name has private access in Passport
 
        p.name  = "Adam";
 
        ^
 
org/police/passportsystem/test/PassportTest.java:13: error: birth has private access in Passport
 
        p.birth = "1994-01-01";
 
        ^
 
2 errors
 
</syntaxhighlight>
 
#: We are not allowed to change the values of private variables.
 
#: ''Note that the error message may differ between different compilers and versions''
 
 
</div>
 
</div>
 
 
==Section: defining constructors==
 
===Description===
 
This section deals with constructors and the syntax and semantics involved. As constructors are one of the basic building blocks for (many) classes, it is important to learn and understand how to declare them.
 
 
The role of constructors is to define how objects can be created from the class. Constructors are run (the code in the constructor executes) when client code creates an instance from a class using the operator called <code>new</code> as we have seen in previous chapters. It is often in the constructor objects are given their initial state. It is common that a constructor declares parameters so that client code can pass the initial values for the initial state of the object.
 
 
To allow for flexibility, a class can declare more than one constructor where the constructors differ in the type and number of arguments which can be passed to the constructor. This can provide means to create objects passing along varying information to the initial state. To declare variations of constructors or methods in this way, is sometimes called overloading.
 
 
The class java.lang.String serves as an example. It declares many overloaded constructors, which gives us flexibility in how we can construct a String object. There is one constructor without any parameters at all which simply creates an "empty string". Then there is one constructor which takes a reference to another String object as the only parameter, which allows us to create a new String as a copy of some other existing String object. And then there's one constructor which takes a reference to an array of char as the argument, which allows us to create a String object representing the characters found in the array.
 
 
If we don't declare any constructors at all, the compiler will actually provide one for us (with no arguments). This is a kind of convenience feature, which allows us to create new objects (with no data provided for initial state) without having to write code for a constructor which seemingly does nothing in the body of the constructor. If we declare at least one constructor, the compiler won't, however, provide any constructor for us.
 
 
When we say that the compiler provides a constructor for us, it is important to know that the constructor will be inserted in the resulting class file from the source code file. The compiler will not ever insert any code in our source code files!
 
 
The syntax of a constructor is:
 
<pre>
 
<access-modifier> ClassName(<parameter-list-if-any>){
 
  <code-for-initialization>
 
}
 
</pre>
 
 
Typically, the access modifier is the keyword <code>public</code> which means that the constructor is available in client code in any class in a program. It is common to have public constructors, since many classes exist for client code to create objects which they need to solve some task. As you will see in sections below, there are more access modifiers than <code>public</code> which limit what client code is allowed to use the constructor. The "ClassName" in the simplified syntax above, means that the constructors "have the same name" as the class. Alternatively you could think of the class name as the "type" created by the constructor. Regardless, it is a strict syntax rule that the constructor must have the class name before the parentheses around the parameter list.
 
 
The parameter list may be empty. If the constructor has parameters, which are placeholders for any values provided as arguments when creating a new object, they are a comma separated list of the form <code>type variableName</code>. Here's an example of a no-arguments constructor:
 
<source lang="Java">
 
public Greeter(String greeting){
 
  // do something with greeting
 
}
 
</source>
 
In the example above, we show a constructor for the class Greeter, with the access level <code>public</code> (the constructor can be used in code from any other class), and a parameter list of one single argument, a reference to a String which will be referred to in the body of the constructor as <code>greeting</code>. When you declare arguments, the arguments become local variables which may be used only in the body of the constructor (or method). Let's explain that with other words! The purpose of parameters is to allow for data to be passed from one place in a program (perhaps in the main method) to code in some other place (perhaps a constructor in a class in some package imported from main). The calling code "passes data as arguments" to, for instance, code for a constructor in another class. The code for the constructor must have a way to reference (talk about) the data sent to it. This is done by declaring parameters with a type and a name, like <code>String greeting</code> in the constructor example above. The parameter <code>greeting</code> will work like a variable local to the constructor code. It will get it's value when and if some other code calls the constructor using the operator <code>new</code>. A local variable, as we've discussed in previous chapters, is a variable that is known only in some block, and as a result only can be used in that block.
 
 
A closer look at the Greeter example. The purpose of a constructor, as the one above, is to give the object being created by the constructor, an initial state. This is often done via parameters whose values are stored in an instance variable for the class. See the section about instance variables for information on the syntax and semantics of instance variables. Let's say that an instance of class Greeter is capable of responding to the action (or message) <code>greet()</code>. The object could for instance play a sound with a greeting phrase or output some greeting to standard out. But where is this greeting phrase stored, and how does it get initialized?
 
 
An object typically stores the data it needs to accomplish some task in so called instance variables declared in the class. Typically, it is the role of the constructor to accept the initial value of the data via some parameter. The block of the constructor then uses the parameter name as a variable and assigns the value to some suitable instance variable.
 
 
In order for the code in the constructor to be able to refer to instance variables, Java uses the keyword <code>this</code> and a dot and then the name of some instance variable. Let's take a closer look at how the Greeter class could accomplish this:
 
 
<source lang="Java">
 
public class Greeter{
 
  private String greeting; // instance variable to store this object's greeting phrase
 
 
  // Constructor accepting a String reference to some greeting text
 
  public Greeter(String greeting){
 
    // store the parameter in the instance variable
 
    this.greeting = greeting;
 
  }
 
}
 
</source>
 
 
You may be surprised that the instance variable has the same name as the parameter. This would be very problematic if it wasn't for the keyword <code>this</code>! But using the keyword <code>this</code>, we have a way to refer to instance variables of the object being constructed by the constructor! You can read the code <code>this.greeting</code> out loud as "this object which is being constructed here has an instance variable called greeting". Now, the statement <code>this.greeting = greeting;</code> clearly (we hope) means that this object's instance variable "greeting" should be assigned the value of the parameter "greeting". Now, we also learn that when the name "greeting" is being used without the "this" keyword, it refers to the parameter.
 
 
One way to think about that is that when we use a name in some block of code, the name refers to the variable declared in the closest scope (or block). The parameter named "greeting" is declared in the constructor which must be the closest block/scope. The instance variable with the same name is declared in the enclosing block (the block of the class definition). So when we use the name "greeting" in the constructor, we mean the parameter. It is the "closest" variable declared with that name. If we want to use the instance variable with the same name, we had to use the "<code>this</code>" keyword since the instance variable is not declared in the closest scope.
 
 
Wouldn't choosing different names for the parameter and the instance variable solve all this without the need for the <code>this</code> keyword, you may ask. Of course, but this is a book about Java and the way Java works, so we don't want to give you the (false) idea that the parameter names must differ from the instance variables. In fact, we could use the <code>this</code> keyword anyway to refer to an instance variable with a different name. The <code>this</code> keyword always refers to "this object". Here's the same class with a different name of the parameter:
 
<source lang="Java">
 
public class Greeter{
 
  private String greeting; // instance variable to store this object's greeting phrase
 
 
  // Constructor accepting a String reference to some greeting text
 
  public Greeter(String aGreeting){
 
    // store the parameter in the instance variable
 
    this.greeting = aGreeting;
 
  }
 
}
 
</source>
 
 
Here, the parameter is called "aGreeting" and the instance variable is called "greeting". So we don't have to use the <code>this</code> keyword, '''but we can anyway'''. Using <code>this</code>, even though we don't have to, could help to make the code clear actually. Now that we told you, you know that <code>this.greeting</code> must refer to an instance variable. There are other uses of <code>this</code> but this is not the place to talk about those. The important part here is that <code>this</code> always means "this object".
 
 
Note that in all the examples above, we didn't include a package statement, to keep our code focused on the constructor. Normally it would be the first line of code in the source code file and precede the class declaration <code>public class Greeter{</code> . And, by all means, note that objects created from the stupid example class can't actually do anything with the greeting text, since we haven't written any methods with code that does something with the instance variable. The objects would only store some text but we could never access that text. We apologize for this.
 
===Videos===
 
* TODO: Video about declaring constructors
 
===Exercises on declaring constructors===
 
 
#As usual, start by creating a directory for these exercises, so that you keep your home directory organized. Use <code>cd</code> to enter that directory.
 
 
# Edit your test class so that the main method looks like this:
 
#:<syntaxhighlight lang="Java" line="1">
 
    public static void main(String[] args) {
 
 
 
        Member m = new Member();
 
        System.out.println(m);
 
 
    }
 
</syntaxhighlight>
 
# Compile the Member and MemberTest classes and run the MemberTest program again.
 
# Write a public constructor with no arguments to your Member class. The instance variables should be made private.
 
# Compile the Member and MemberTest classes and run the MemberTest program again. Did you see a change in the printout? Why?
 
# In order to set the instance variables we need to pass information to the constructor. Add two parameters (String newname and String newEmail) to your member constructor. Use these parameters to set the corresponding instance variables. Recompile your classes and run the memberTest program again. Why does the compilation fail?
 
# Add the arguments "Ada" "ada@lovelace.edu" in your MemberTest code, where your're creating the Member instance. Recompile your classes and run the memberTest program again
 
# Make sure that the parameters to the Member constructor are called the exact same thing as the instance variables. That is the code should look something like this:
 
#:<source lang="Java">
 
  public Member(String name, String email) {
 
    name  = name;
 
    email = email;
 
  }
 
</source>
 
#: Compile and execute the code again. Did it work?
 
# Now change to the following in your constructor:
 
#:<source lang="Java">
 
  public Member(String name, String email) {
 
    this.name  = name;
 
    this.email = email;
 
  }
 
</source>
 
#: Do you see the word <code>this</code>? This word <code>this</code> is used to say to the compiler that we, the developers, mean the instance variable <code>name</code> and not something else. Do you think that the code will work now?
 
# Ok, but what about email. If a Member has no email address, what do we do then? We suggest (for now) to add a constructor with only one parameter (the new name).
 
# Nice. But some code is duplicated, see below:
 
#:<syntaxhighlight lang="Java" line="1">
 
  public Member(String name, String email) {
 
    this.name  = name;
 
    this.email = email;
 
  }
 
 
  public Member(String name) {
 
    this.name = name;
 
  }
 
</syntaxhighlight>
 
#: Is there a way for us to reuse the code of one constructor in another? Yes, there is. We will show you how to do it and we ask you to think about it and in coming Passport exercise implement it yourself.
 
#:<syntaxhighlight lang="Java" line="1">
 
  public Member(String name, String email) {
 
    this(name);
 
    this.email = email;
 
  }
 
 
  public Member(String name) {
 
    this.name = name;
 
  }
 
</syntaxhighlight>
 
#: On line 2 we call the other constructor with the name argument. What about the keyword <code>this</code> - wasn't it used to instruct Java that we (the developer) want to refer to an instance variable? Well, it is but think of <code>this</code> as something referring to the current object - in the case of a constructor it is the object being created and in the case of a method it is the object on which the method was invoked).
 
#: But if we use different name (e g newName and name) we will not need to use <code>this</code>? Well, you're right but we (the authors) believe it is good to use this to make it easy for someone reading our code that we for example mean to use the instance variable).
 
# Email address - do we know something about email addresses? It always contain the <code>@</code> sign. So an email address without @ is not an email address. Should we allow someone to set an invalid email address? No, we should not so let's add code to check if there is an @ present in the email address given as argument to the constructor (see below):
 
#:<syntaxhighlight lang="Java" line="1">
 
  public Member(String name, String email) {
 
    this(name);
 
    // Check for valid email
 
    this.email = email;
 
  }
 
</syntaxhighlight>
 
#: Compile and execute the code again to make sure it works.
 
# In your TestMember class we want you to create one more Member with the name "Charles" and the (invalid) email address "charles _AT_ babbage.net". This code will check if your email checking code works - i e the new Member should not have an email address "stored" since the one above is invalid.
 
#: Ok, good we now have made sure that the emails address must be correct. But for a developer using our Member class it might be useful, or even crucial, to be notified if a method invocation (calling a method) went wrong. How do we do this? Some authors have a tendency to use return values for this but we will use the preferred way in Java, which is using something called Exceptions which is dealt with in coming chapters. 
 
# Try adding a new member (in your Membertest class, like this:
 
#:<syntaxhighlight lang="Java" line="1">
 
      Member noone = new Member("Dummy", null);
 
      System.out.println(noone);
 
</syntaxhighlight>
 
#: Will it work? Why?
 
#: We will deal with writing robust code in future chapters. With robust code we mean code that will "always" work.
 
# In the previous section you wrote a Passport class and a class to test that. We now want you to add the following to the Passport class:
 
#: * make the variables (name and birth) private
 
#: * a constructor with name and and birth as parameters
 
#: Compile the Passport class to make sure it is (syntactically) ok.
 
# Try to compile the "old" PassportTest class. Do you think it will work? Check and see.
 
# Change the TestpassportTest class so that it creates a Passport using the new constructor.
 
#: Output the Passport object using <code>System.out.println</code>.
 
# Add a method (<code>public String toString()</code>) like you did in Member. Compile both classes and make sure it compiles and executes properly.
 
# Let's look a bit again at the Greeter class we've used before. Now it is you who should write it. Create the following directory structure:
 
<source lang="bash">
 
.
 
`-- org
 
    `-- progund
 
        |-- greet
 
        `-- main
 
</source>
 
#: You can create the whole structure using only two commands:
 
#: <source lang="bash">
 
$ mkdir -p org/progund/greet/
 
$ mkdir -p org/progund/main/
 
</source>
 
#: In the "org/progund/greet/" directory, create a Java source code file with the declaration of the Greeter class. It should have a package declaration as the first line in the code declaring that the class belongs to the package "org.progund.greet". The class should be publi and have the name Greeter. This means, as usual, that the source code file must be called "Greeter.java". Write an instance variable declaration for a reference to a String containing a greeting text. You may use the same name for the variable as in the example.
 
# Write a "public" constructor which accepts one parameter, a reference to a String. In the constructor body, assign the value of the parameter to the instance variable. Compile the class from the exercise directory (meaning that you need to give the compiler the relative path to the source code file). Make sure it compiles.
 
 
===Solutions to declaring constructors===
 
<div class="mw-collapsible mw-collapsed">
 
Expand using link to the right to see the full content.
 
<div class="mw-collapsible-content">
 
 
# The MemberTest class should now look like this:
 
#:<source lang="Java">
 
package net.supermegacorp.orgmanager.test;
 
 
import net.supermegacorp.orgmanager.Member;
 
 
public class MemberTest {
 
 
    public static void main(String[] args) {
 
 
        Member m = new Member();
 
        System.out.println(m);
 
    }
 
 
}
 
</source>
 
# To compile and execute the MemberTest class you type the following:
 
#:<source lang="bash">
 
javac net/supermegacorp/orgmanager/test/MemberTest.java net/supermegacorp/orgmanager/Member.java && java net.supermegacorp.orgmanager.test.MemberTest
 
null null
 
</source>
 
# It is hard to find something meaningful in doing the below:
 
#:<source lang="Java">
 
 
  public Member() {
 
  }
 
</source>
 
#: But we will use the results to "prove" a point.
 
# The printouts are the same. We wanted to show you that if you do not write any constructor, Java creates a default constructor for you - a constructor with no arguments.
 
# Your Member class should now look something like the following:
 
#:<source lang="Java">
 
package net.supermegacorp.orgmanager;
 
 
public class Member {
 
 
  private String name;
 
  private String email;
 
 
  public Member(String newName, String newEmail) {
 
    name = newName;
 
    email = newEmail;
 
  }
 
 
  public String toString() {
 
    return name + " " + email;
 
  }
 
 
}
 
</source>
 
#:The compilation fails since we're calling a constructor with no arguments and we have no such constructor. But before we added any constructor, in the earlier section about declaring variables, we could call such a constructor. Java is kind enough to add a constructor with no parameters for us if (and only if) we haven't written any constructors. This automatically added constructor is called ''default constructor''. You will see in some literature and examples that you "must" write such a constructor yourself but don't be fooled by this. People claiming this do not know the rules of Inheritance well enough to teach it. But don't worry - WE DO ;) So how do we solve the failing compilation? Let's look at the next exercise.
 
# The MemberTest class should look something like this:
 
#:<source lang="Java">
 
package net.supermegacorp.orgmanager.test;
 
 
import net.supermegacorp.orgmanager.Member;
 
 
public class MemberTest {
 
 
    public static void main(String[] args) {
 
 
        Member m = new Member("Ada", "ada@lovelace.edu");
 
        System.out.println(m);
 
    }
 
 
}
 
</source>
 
# It will compile but not function the way we want since we're setting the value of the instance variables to the values of the instance variables. Setting the value of a variable x to the value of just x will not change a thing Same here. Java uses the last "known" or "seen" declaration of a variable - and between the instance variable and the parameter the latter is the last one seen, so the parameter is used. 
 
# It will work now, since we're setting the value instance variable <code>name</code> (we're using <code>this.name</code> to <code>name</code> which, without the <code>this</code> keyword, refers to the parameter named <code>name</code>
 
#:<source lang="Java">
 
  public Member(String name, String email) {
 
    this.name  = name;
 
    this.email = email;
 
  }
 
</source>
 
# The new Member constructor should look something like:
 
#:<source lang="Java">
 
  public Member(String name) {
 
    this.name = name;
 
  }
 
</source>
 
#: Note that this constructor only sets a value to name and leaves email unset. What happens with our nice toString method? We'll skip the discussion on this since we'll be doing that in the chapter on inheritance.
 
# Nothing to do in this exercise.
 
# Suggested solution:
 
#:<source lang="Java">
 
  public Member(String name, String email) {
 
    this(name);
 
    if (email.contains("@")) {
 
      this.email = email;
 
    }
 
  }
 
</source>
 
#: Lets anaylse the following a bit further:
 
#:<source lang="Java">
 
    if (email.contains("@")) {
 
      this.email = email;
 
    }
 
</source>
 
#: The code <code>email.contains("@")</code> invokes the <code>contains</code> method with <code>"@"</code> as argument. Doing this means we state that the email object contains "@". If the String email contains "@" the statement is <code>true</code> and if "@" was not present the statement is <code>false</code>.
 
#: So when we write
 
#:<source lang="Java">
 
    if (email.contains("@")) {
 
</source>
 
#: We only reach inside the block if the email address really contains "@" (i e the statement is true), so we can now to the instance variable email assign the value of the argument, which is done here:
 
#:<source lang="Java">
 
      this.email = email;
 
</source>
 
#: and of course we need to "close" the block:
 
#:<source lang="Java">
 
    }
 
</source>
 
# Suggested solution:
 
#:<source lang="Java">
 
      Member charles = new Member("Charles", "charles __AT__ babbage.net");
 
      System.out.println(charles);
 
 
</source>
 
# It will not work since eventually the line
 
#:<source lang="Java">
 
    if (email.contains("@")) {
 
</source>
 
#: will be executed. Since email is null we get a runtime error (actually a so called exception). More on this in coming chapters. We just wanted to give you a heads-up.
 
# Suggested solution:
 
#:<source lang="Java">
 
package org.police.passportsystem;
 
 
public class Passport {
 
 
  private String  name;
 
  private String  birth;
 
 
  public Passport(String name, String birth) {
 
    this.name  = name;
 
    this.birth = birth;
 
  }
 
}
 
</source>
 
# The PassportTest class calls the default constructor (a constructor with no arguments automatically created by Java if (and only if) there are no constructors defined by the developers in the class). Since there no longer is such a constructor - since we have defined a constructor by our own (and Java only creates a default constructor with no arguments if and only if there are no constructors as defined by the developer) - the compilation will fail.
 
# Suggested solution:
 
#:<source lang="Java">
 
package org.police.passportsystem.test;
 
 
import org.police.passportsystem.Passport;
 
 
public class PassportTest {
 
 
    public static void main(String [] args) {
 
 
      Passport p = new Passport("Adam", "1994-01-01");
 
      System.out.println(p);
 
 
    }
 
 
}
 
</source>
 
# Suggested solution:
 
#:<source lang="Java">
 
package org.police.passportsystem;
 
 
public class Passport {
 
 
  private String  name;
 
  private String  birth;
 
 
  public Passport(String name, String birth) {
 
    this.name  = name;
 
    this.birth = birth;
 
  }
 
 
  public String toString() {
 
    return name + " " + birth;
 
  }
 
}
 
</source>
 
# For instance, your class could look like this:
 
#:<source lang="Java">
 
package org.progund.greet;
 
 
public class Greeter{
 
 
  //Instance variable to hold the greeting text:
 
  private String greeting;
 
 
  // Constructor accepting a String reference to some greeting text
 
  public Greeter(String greeting){
 
    // store the parameter in the instance variable
 
    this.greeting = greeting;
 
  }
 
}
 
</source>
 
#: Note that this stupid class can't do anything with the greeting text, because we have't written any methods yet!
 
</div>
 
</div>
 
 
==Defining methods==
 
 
===Description===
 
More about the syntax and structure of methods. Overloaded methods. Whatabout static methods. TODO: Write full description.
 
 
Draft sketch for presentation:
 
* named instruction list
 
* pass information
 
* return information
 
 
===Videos===
 
TODO: Video about declaring methods
 
===Exercises on declaring methods===
 
 
Let's go back to our Member class.
 
 
# Imagine you would like to get hold of the name of an object. Or the email. How do we do that now? We need to add methods (public methods so everyone can use them).
 
#: * Write a method <code>public String name()</code> that returns the name
 
#: * Write a method <code>public String email()</code> that returns the email address
 
#: In some books and traditions it seems as if the name for such methods must be <code>getName()</code> and <code>getEmail()</code> and often with corresponding set methods <code>setName(String name)</code> and <code>setEmail(String email)</code>. We have never been able to justify this so we're simply avoiding this. See [[Setter and Getters]] for more information.
 
# Write some simple tests of these methods in your MemberTest class.
 
# It would be nice to be able to update a Member's email address. We don't think it is necessary to change the name since that really doesn't happen that often so when it does we can create a new object instead and "throw away the old one". So add a method, <code>setEmail(string email)</code> to set an object's email address. Make sure that the email address is valid.
 
# The code to check the validity of the email address in the setEmail method and in the constructor are similar. Let's reuse the code. Make a call in the constructor to the method. This way you will have only one code to check the email validity.
 
# Let's say that we don't like the look of the String returned by <code>toString</code>. For some reason we would like the vales (of name and email) to be separated by ";" instead. Change the toString method to do this.
 
# The change was relatively easy in the previous exercise, wasn't it? Let's say we had three, four, five or even more instance variables (variables specific to a specific instance). It means that we need to change the " " (space) to ";" (semi colon) in quite a few places. How about keeping this separator in a variable instead... and that is your next task. Create a String variable called <code>separator</code> that has the value ";".
 
# In the previous exercise each object has its own variable separator with the value ";". This is not optimal if we consider memory space. One could also discuss if this really is a variable that belongs to an object. Perhaps the class should be responsible for storing this. Can a class store a variable? We'll continue this discussion under static variables and methods.
 
# In the previous section you wrote a Passport class and a class to test that. We now want you to add the following to the Passport class:
 
#: * public methods to retrieve the birth and name variables
 
#: * (OPTIONAL) a method returning (as an int) the age of a person to which the Passport belongs (use the birth variable to calculate this)
 
 
===Solutions to declaring methods===
 
<div class="mw-collapsible mw-collapsed">
 
Expand using link to the right to see the full content.
 
<div class="mw-collapsible-content">
 
# Suggested solution:
 
#:<source lang="Java">
 
  public String name() {
 
    return name;
 
  }
 
 
  public String email() {
 
    return email;
 
  }
 
</source>
 
# And some tests:
 
#:<source lang="Java">
 
      System.out.println("Ada's name:    " + ada.name());
 
      System.out.println("Ada's email:    " + ada.email());
 
      System.out.println("Charle's name:  " + charles.name());
 
      System.out.println("Charle's email: " + charles.email());
 
</source>
 
# Suggested solution:
 
#:<source lang="Java">
 
  public void setEmail(String email) {
 
    if (email.contains("@")) {
 
      this.email = email;
 
    }
 
  }
 
</source>
 
# Here's the constructor:
 
#:<source lang="Java">
 
  public Member(String name, String email) {
 
    this(name);
 
    setEmail(email);
 
  }
 
</source>
 
# .. passport solutions
 
</div>
 
</div>
 
 
==Static variables and methods==
 
 
===Description===
 
 
===Videos===
 
 
===Exercises on static variables and methods===
 
 
Let's go back to our Member class. We added a variable separator that we used to store the separator between values in our printout. We also discussed if we needed to have one separator variable per object. We don't. Instead we can let the class have a variable common for every object. This means that this variable belongs to (is associated with) the class instead of a separate object.
 
 
# Change the <code>separator</code> variable into a class variable, using the keyword <code>static</code>.
 
# Let's assume someone wants to know what separator is used when calling <code>toString</code> on Member objects. To let people get this value we can either:
 
#: * make the variable public. A drawback of this is that people can change it. This makes it not usable for us.
 
#: * keep the variable private and add a public method, <code>getSeparator</code>.
 
#: Your job is to write the method as described last. Should this method be public or private? Should it be static or non-static?.
 
 
===Solutions to static variables and methods===
 
 
<div class="mw-collapsible mw-collapsed">
 
Expand using link to the right to see the full content.
 
<div class="mw-collapsible-content">
 
 
# Suggested solution (parts of the class):
 
#:<source lang="Java">
 
package net.supermegacorp.orgmanager;
 
 
public class Member {
 
 
  private String name;
 
  private String email;
 
  private static String separator = ";";
 
 
  public String toString() {
 
    return name + separator + email;
 
  }
 
}
 
</source>
 
# Suggested solution (parts of the class):
 
#:<source lang="Java">
 
package net.supermegacorp.orgmanager;
 
 
public class Member {
 
 
  private String name;
 
  private String email;
 
  private static String separator = ";";
 
 
  public static String getSeparator() {
 
    return separator;
 
  }
 
 
  public String toString() {
 
    return name + separator + email;
 
  }
 
}
 
</source>
 
#: We need to make the method public since we want others to be able to use it. It does not have to be static since all objects can reach the class, but we suggest making it static to reflect that the variable is static.
 
</div>
 
</div>
 
 
==Section: final variables and methods==
 
 
===Description===
 
 
===Videos===
 
 
===Exercises on final variables and methods===
 
 
Let's go back to our Member class. We added a variable separator that we turned into a static variable, in the previous section. Why should anyone, including ourselves, be able to change it? We (the authors) see no reason to be able to change it. So let's make the variable "unchangeable".
 
 
# Make it impossible to change the <code>separator</code> variable. Do this by using the keyword <code>final</code>.
 
 
''Note: a method can also be final but this does not make sense before we introduce inheritance so we'll skip it for now''
 
 
===Solutions to final variables and methods===
 
 
<div class="mw-collapsible mw-collapsed">
 
Expand using link to the right to see the full content.
 
<div class="mw-collapsible-content">
 
 
# Change the <code>separator</code> declaration to look something like this:
 
#:<source lang="Java">
 
  private static final String separator = ";";
 
</source>
 
 
 
</div>
 
</div>
 
 
==About Java packages==
 
 
===Description===
 
Now we have seen some rules on how to write and declare classes. It is time to talk about the roles of the different parts! We'll start by talking a little about packages... grouping related classes together in units stored in directories. TODO: Write full description
 
 
===Videos===
 
 
# TODO: Video talking about the role of Packages [ (eng)] [ (sv)] [[Media:Packages.pdf|(download presentation)]]
 
 
===Exercises on grouping stuff in packages===
 
This exercise aims to make you familiar with the concept of packages...
 
 
# Question 1
 
 
===Solutions to grouping stuff in packages===
 
<div class="mw-collapsible mw-collapsed">
 
Expand using link to the right to see the full content.
 
<div class="mw-collapsible-content">
 
 
# Solution to exercise 1...
 
</div>
 
</div>
 
 
==Testing if your classes work==
 
Write test code in a separate class with a main method. TODO: write a full description.
 
===Exercises on testing your classes===
 
This exercise aims to make you familiar with how to write test code to test your classes.
 
 
# Question 1
 
 
===Solutions to Testing your classes===
 
<div class="mw-collapsible mw-collapsed">
 
Expand using link to the right to see the full content.
 
<div class="mw-collapsible-content">
 
 
# Solution to exercise 1...
 
</div>
 
</div>
 
 
==Using our classes==
 
Now that we have seen the rules on how to write classes with variables, constructors and methods, we'll look a little at how we use these classes in programs which actually do something. How do we write programs using our own classes?
 
* Typically there is only one main in a separate class (not counting tests).
 
* typically the Main class (class with the main) is in a separate package
 
** typically you need a package statement here too because of that
 
** typically you need import statements in the Main class (also because of that)
 
* Other normal classes (classes we write that don't have the main method) often also uses other classes
 
** If we write a class, it probably needs more classes which we also write ourselves
 
** Related classes are in the same package and can "use" eachother without import (otherwise we need that)
 
** One use can be as a return type for a method
 
** Another use can be as the type of an instance variable
 
===Exercises on using your own classes===
 
This exercise aims to make you familiar with how to write programs which make use of the classes you define yourself.
 
 
# Question 1 TODO: write questions
 
 
===Solutions to using your own classes===
 
<div class="mw-collapsible mw-collapsed">
 
Expand using link to the right to see the full content.
 
<div class="mw-collapsible-content">
 
 
# Solution to exercise 1...
 
</div>
 
</div>
 
 
 
==Looking at the source code for some API classes==
 
===Description===
 
To demystify source code for classes we show briefly the source code for some classes in the API. We also show how to find the source code in src.zip (or how to get it).
 
 
* java.lang.String (quick glance)
 
* java.lang.System (quick glance)
 
* java.lang.Math (quick glance - focus on private constructor and all the static methods)
 
===Videos===
 
# TODO: make video examining the source briefly for String, System and Math (showing some simple uses of variables, constructors and methods (including a discussion of the use of <code>static</code>.
 
 
===Exercises on the source code for API classes===
 
TODO: Write an exercise on how to obtain the src.zip and ask the students to investigate some classes.
 
===Solutions to looking at the source code for API classes===
 
<div class="mw-collapsible mw-collapsed">
 
Expand using link to the right to see the full content.
 
<div class="mw-collapsible-content">
 
# TODO: write Solution to exercise 1...
 
</div>
 
</div>
 
 
== Other keywords related to classes ==
 
 
* finalize
 
* volatile
 
* native
 
* transient
 
* synchronized
 
  
 
=Chapter Links=
 
=Chapter Links=
Line 1,565: Line 558:
 
==Books this chapter is a part of==
 
==Books this chapter is a part of==
 
=== Programming with Java book ===
 
=== Programming with Java book ===
[[Programming_with_Java#Chapters|Book TOC]] | [[Chapter:Objects in Java|previous chapter]] | [[Chapter:Inheritance|next chapter]]
+
[[Programming_with_Java#Chapters|Book TOC]] | [[Chapter:Objects in Java|previous chapter]] | [[Chapter:_Classes_II|next chapter]]

Latest revision as of 14:31, 24 June 2017

THIS PAGE IS REPLACED BY:

Meta information about this chapter

Expand using link to the right to see the full content.

Introduction

Classes are of course a very central topic in a book on Java and Java programming. It is, in fact, one of the larger topics and very heavy on syntax and semantics. We want to cover the topic on classes in its entirety but will will focus on the basics and just touch upon the heavier and more advanced stuff like nested and inner classes.

The focus of this chapter is to teach how to write your own classes and we start off by talking about the syntactic layout of class source code files. After this, we zoom in on stuff like variables (instance variables and class variables), constructors and methods (instance and class methods).

The idea is to give the students an understanding of how to declare a class, what are the different parts of a class, i.e. what declarations can exist in the class block, and an introduction to the declaration and function of those parts.

Purpose

The purpose of including this chapter is to give the students the basic knowledge needed to construct classes of their own. This is so essential to Java programming, that without this knowledge, very little can be done. After learning how to use someone else's classes to construct objects and put those objects to work, it is now time to provide the tools for knowing how to create classes from scratch (for use by the student's own programs or for use by other people).

Goal

The student shall after completing this chapter be able to:

  • Understand the basic building blocks of classes:
    • variables (instance and static)
    • constructors
    • methods (instance and static)
  • Construct basic classes containing the basic building blocks
  • Recognize the most basic Java keywords and understand the contexts where they can occur
  • Understand the concept of access modifiers (at least private and public)
  • Declare and use:
    • Variables (instance and static) and constants
    • Constructors
    • Methods (instance and class)
  • Understand the next chapters about inheritance and interfaces

Instructions to the teacher

Common problems

It's important that the student understands the difference between classes and objects. Compiled java source code files are called class files, which can be confusing unless this is addressed. Talking about the source code for a class and the class as seen by the JVM in runtime can be very confusing, since it is the class code the students are used to reading and writing, while a runtime class acts both as a type and API towards objects. Also, it is important to remind the student that a reference variable may refer to an object of some class or null. We want to stress once again that what we say has a great impact on what the students understand. Even if it becomes tedious and bureaucratic to say stuf like "toString() returns a reference to a new String with a String representation of the ojbect", this is in our experience something which the students (and sometimes even more experienced programmers) need to hear over an over again. It doesn't hurt to remind the students of this relation from time to time.

Another thing to think about is that an object is the same as an instance of a class. When alternating by calling the object "an object" and "an instance", it is not wrong to remind the students that objects and instances are synonyms in Java.

One big issue when learning programming and Java is to mentally switch between what happens in compile time and what happens in runtime. A problem for us teachers, is that we often show source code and ask questions like: "What happens when this line of code executes?". Even though we know that the Java source code resides in a class in a source code file which will be compiled to byte code in a class file, and only at runtime will that class eventually be loaded by the JVM, which in turn at some time will execute the code we were talking about, this is something we sometimes forget to point out to the students. The danger with this, of course, is that the students may subconsciously get the idea that the source code will be interpreted as it is. This, in turn, may lead to confusion about the difference between compile time (which is where we are when we look at source code) and runtime, because the code looks the same when the teacher is talking about it!

An additional potential problem with understanding all this, is polymorphism in the sense that a reference variable has the compile time type "Reference to some class" when the actual type of the object referred to at some point during runtime may have the type of a subclass to the reference type. This will be addressed in the chapters about inheritance and interfaces, but it is worth thinking about even in earlier chapters, because it is in early chapters we have the chance to lay the foundation for understanding compile time, runtime, compile time type, runtime type. The point here is that if you don't understand the difference between compile time and runtime (or maybe even also design time), it will be very hard to grasp the concept of polymorphism when it's time for that.

Understanding the difference between static members and instance members is often hard for students. First it is hard to understand what the semantic difference is, and the difference in runtime. Second, once the students understand the implication of a variable or method being static, they are faced with knowing when to choose "instance or static". It isn't obvious for new students (or sometimes even experienced programmers) to motivate when in particular a method should be static and when it shouldn't. It doesn't help that many books (for more or less natural reasons) start with the main method as a self-contained program, only to move on to refactoring the program by factoring out parts of the code to static methods in the same (and only) class as the main method.

One way of explaining how to choose between static or instance context for a method is to focus on the data which the method operates on. Methods that only operate on data provided as arguments (and that have no side effects) are good candidates for being static methods. Methods whose operations depend on the state of some object are more likely to be instance methods. Now, the latter depends of course on an understanding on grouping data and behavior together as objects. So we could rephrase the second rule about instance method candidates to, "Methods that constitute the operation you can perform on an object, the messages you can send to an object, are candidates for being instance methods, because they often need access to the state of the object in order to do their work". Another possible rephrasing could be "Methods declared in the same class as the type of the object, and whose operations depend on the state of that object, must be instance methods".

Another, perhaps more simplistic, way of explaining when to use a static method is to say "when you don't need to have access to any specific object in order to run a method, this method must be static". But this is just a rephrasing of the previous statement. The central part to understand is that method which change or use the data of a specific object, as part of this objects behavior, must be an instance method. Instance methods are tied to instances, as implied by the name. They offer a way to use or change an instance's state.

Note, though, that passing a reference to an object as a parameter to a static method, which in turn uses the state of the object, could also be described as the method "depending on the state of an object". This was of course not the intent of the rule. The rule only applies to methods "declared in the same class as the type of the object".

Once the students understand that you can have many objects of the same class, and that those objects can have different state, it is easier to explain that instance methods are applied to the instances even if they are declared in the class. Static methods, on the other hand, can be called regardless of even the existence of instances, so they can't depend on instance variables or references to instances.

A particular surprising but telling example is the classic quiz question What will be the result of compiling and running the following program:

 1 public class Example{
 2   public static void main(String[] args){
 3     Example ex = null;
 4     System.out.println( aMethod(ex) );
 5   }
 6   static String aMethod(Example e){
 7     return e.aNotherMethod();
 8   }
 9   static String aNotherMethod(){
10     return "Awooga";
11   }
12 }

Many would jump to the conclusion that there will be a NullPointerException on line 7, because the parameter e is null. But static methods can be called even via Null references, since the static method doesn't need or care about dereferencing the reference variable e - it needs only to know the type of e.

We have tried to sneak in a style in previous chapters and examples which lets the main method create objects of some class, and let the objects do the work. We actually believe that merely avoiding a lot of calls to static methods from the main method helps giving the students a better preparation for understanding the difference between static methods and instance methods. It is our belief that instance methods are more common than static methods(this certainly seems to be the case, looking at the Java API) and perhaps should be merited more attention for this reason alone.

When showing calls to static methods, such as mathematical functions in java.lang.Math, it is good to make a point about those methods being static and elaborate on that. For instance one can mention that it would be tedious to have to create a Math object just to get access to the mathematical functions (which are pure functions and don't depend on any state and don't have any side effects). One can also elaborate on what it would mean if it were possible to create Math objects - could there be more than one instance of "Math"? What would that mean? This is also a good time to show that it is not possible to create Math instances. Ask the students if they can guess how the class is defined in order to prevent instantiation (the answer is that it has a private constructor of course). Later, when talking about inheritance, one could ask the students if one may extend Math. If not, how is this achieved? Repeat the meaning of finalwhen used in a class declaration.

Chapter Videos

See below for individual links to the videos.

Description

Class declaration

In the previous chapter we introduced objects and classes so we should all have a basic idea of what objects and classes are.

The chapters on classes deals with the components of a class and the source code layout for a class declaration. What parts constitutes a class? Before we answer that, we start by looking at what are the parts of a class as defined in a source code file. A Java class definition in a source code file can contain the following elements:

  • A package declaration - declares logical association expressed as a package (which corresponds to the path to the class file)
  • import statements (if needed)
  • The actual class declaration with the class name and the start of the block of code for the class
  • The variables needed to keep the state of objects created from this class (instance variables)
  • The variables common (shared, will exist in only one copy) to all instances created from this class (static variables)
  • The constructor(s) providing means to create instances from this class
  • The methods of instances of this class - what objects of this class can do
  • The methods which exist independently from instances of this class (methods which don't involve instances of this class)
  • Nested and inner classes - a class definition can actually contain other classes - this is outside of the scope for this book
  • Initializers - you can actually put blocks of code directly in the class body - this is outside of the scope for this book

We'll discuss these components one by one, in the chapters on Classes. Note that the last two components are only included here in order for us to be more complete. We don't want to hide these components for you, but we will not go into any details about the use of them in the scope of this book.

Package declaration

Video

Description

Imagine there are two classes with the same name and you want to use them both. Actually this is the case already in Java with a class called Date. In Java this is solved by adding an extra name to the class, we use the package construction. The two classes are java.util.Date and java.sql.Date and by using packages we can use them both.

Also imagine if you have a project with some thousand classes. Keeping all the corresponding Java files (the source code) in one directory would make it very hard to get an overview of the source code. Instead we split the project into smaller parts, each responsible for a part of the complete system. To achieve this we use the same construction as above.

We dare say that you will not see a program, in use by real users, that don't use packages. Not using packages is unfortunately something you will see in many books and education material. Since packages are easy to use we're going to use packages for everything we all write in the future - be it examples, exercises, assignments and exams.

A class can contain zero or one package declaration, which has to be the first statement in the source code file for the class. If the class source code doesn't have a package declaration, the class will implicitly belong to a "nameless" package, which could be thought of as "current directory". Packages correspond to the relative location of the compiled source code file. The source code is also saved in a directory structure matching the package name.

A class in the "nameless" package can only be found by the java command (actually by the JVM's so called class loader) if the command is executed in the same directory as the class file (the compiled source code file). A class in an explicit package must be compiled into a directory matching the package name.

A package normally name consists of a series of lower case parts, separated by '.' (dots) leading up to the actual class name, as in org.progund.Game, where Game is the name of the class. Each part leading up to the class name corresponds to physical directories of the same name and structure. If we look at org.progund.Game again, the source code for Game.java should be located in a directory structure as shown below:

.
`-- org
    `-- progund
        `-- Game.java

Note the dot at the top of the directory structure. This is the starting point of the relative path to Game.java. A dot signifies "current directory" in most terminals and shells. This is to say, that if we are in some directory and want to compile Game.java, and Game.java belongs to the package org.progund, we need to make sure that the class file from compiling Game.java ends up in a directory structure according to the package name. Here, the first part of the package is org. So we need to have a directory called "org". The next part is progund, which means that inside "org" we need to have a directory "progund". This means that the dots correspond to the file separator character in a path! On UNIX-like systems (like cygwin), the file separator character is "/" (forward slash). So, the compiled file for org.progund.Game must be located in the relative location org/progund/Game.class.

Now, if the source code file Game.java is in org/progund/Game.java and we are in the current directory as shown above, if we compile the file using the relative path to it:

$ javac org/progund/Game.java

Then, the compiler (if the compilation is successful of course) will put the class file in the same directory as the source code. We will then have a directory structure as shown here:

.
`-- org
    `-- progund
        |-- Game.class
        `-- Game.java

Now, let's pretend that the Game class has a main method, so that we can run it as a Java program. If we want to run it using the java command, we will actually give java the full class name (the qualified name including the package):

$ java org.progund.Game

We saw that the class file which is loaded and run by the JVM invoked by java was located in the relative path org/progund/Game.class but the argument to java was org.progund.Game. This should make it obvious that the dots in the class name corresponds completely to the directory separators!

It is OK if you keep things as described above where the class files end up in the same directory as the source code files. But in the real world, it is actually common to keep two parallel file structures; one for the source code and one for the class files:

.
|-- bin
|   `-- org
|       `-- progund
|           `-- Game.class
`-- src
    `-- org
        `-- progund
            `-- Game.java

Now we've added to extra levels; the bin directory, and the src directory. Note that these are not part of the Java world! They are just there so that we can have two identical directory structures side by side!

If we'd want to run the program using Game.class, we'd have to cd down to the bin directory, so that org.progund.Game still would translate to a valid relative path! If we cd to the bin directory, when the package name is translated to a relative path, the path would still be correct to the file org/progund/Game.class. But if we'd stayed in the directory annotated as "." in the layout above (the directory where both bin and src are located), running java org.progund.Game would yield a "Class not found" error from the java command. This is only natural, because the JVM would translate the qualified name org.progund.Game to a path for the class files org/progund/Game.class. Trying to resolve that path would fail miserably, because there was no org directory in the current directory! Only a bin directory, and a src directory.

Now, there is actually a solution to this too! Java comes with a concept called "class path". If we were in the directory above bin and src, we could actually help java find the org.progund.Game class, by giving it a hint on where to look for the org directory:

$ javac -d bin src/progund/Game.java 
$ java -cp bin org.progund.Game
Game over!
$ ls
bin  src
$ ls bin/org/progund/
Game.class
$ ls src/org/progund/
Game.java

The trick was to provide the class path using the flag -cp bin. That meant "run org.progund.Game but look in bin in order to find the class!".

Videos

Exercises - package declaration

Create the following directory structure:

.
|-- bin
|   `-- org
|       `-- progund
`-- src
    `-- org
        `-- progund

You should remain in the directory signified by "." in above. Download the Game.java source code into src/org/progund (when we say "download a file into a directory", we actually mean that you should download a file and make sure you move it to that directory). Open the file and look at the package declaration. Remember that if there is a package declaration, it must be on the first line of the source code file.

  1. What is the package name?
  2. What is the full (qualified) name of the Game class?
    Use cd to change directory down to src. Compile Game.java from this directory (you need to give javac the full path to the file Game.java!). Still in the src directory, list the contents of the relative path org/progund/.
  3. How many files is in that directory?
  4. What is the names of those files?
    Still in the src directory, run the program Game (Game has a main method!):
    $ java org.progund.Game
    
  5. What is printed to the terminal?
    Delete the class file you just created:
    $ rm org/progund/Game.class
    
    Change directory up one level:
    $ cd ..
    
    Now try this:
    $ javac -d bin src/org/progund/Game.java
    
    Note the flag -d bin! It means that javac should no longer put the class file in the same directory as the source code, but use the bin directory structure instead. Using the package declaration, javac knows that it should put the class file not only somewhere under bin but exactly in bin/org/progund.
  6. How many files are now inside the src/org/progund directory? (use ls to find out)
  7. How many files are now inside the bin/org/progund/ directory?
    Run the program inside bin/org/progund/Game.class For this, you need to use the class path flag -cp bin (since you haven't changed directory down to bin, java would never find the org directory without the -cp bin!).
  8. Did it work?

Solutions to - package declaration

Expand using link to the right to see the full content.

  1. org.progund
  2. org.progund.Game
  3. src/org/progund/ now contains two files.
  4. src/org/progund/Game.java and src/org/progund/Game.class
  5. Game over!
  6. src/org/progund/ now contains one file, Game.java. You just deleted the other one, and you told javac to put the class file in the bin directory structure instead, using the flag -d which stands for "destination".
  7. bin/org/progund/ now contains one file, Game.class. You told javac to put the class file in the bin directory structure, using the flag -d which stands for "destination". So this is the one file!
  8. Of course it worked? If not, please consult with your class mates and/or tutors.

Starting point of a program

Exercises

The starting point for a class is the main method, which has to be declared exactly as Java requires (with the exception that you may chose the name of the parameter).

We have written some exercises to let you played around with the main method and with two main methods.

  1. Write a simple class, called Game, in the package org.gamefactory.textgame. This means that you should have a directory structure as follows:
    `-- org
        `-- gamefactory
            `-- textgame
                `-- Game.java
    
    The class should have no main method.
  2. Compile and execute the class. Did it work? Why?
  3. Add a main method to the class. The main method could simply output the class' name, using println. The code looks something like this:
      public static void main(String[] args) {
        System.out.println("Game");
      }
    
  4. Compile and execute the class. Did it work? Why?
  5. Write one more simple class, called Gamer, in the package org.gamefactory.textgame. This means that you should have a directory structure as follows:
    `-- org
        `-- gamefactory
            `-- textgame
                |-- Game.java
                `-- Gamer.java
    
  6. Add a main method to the new class (Gamer). The main method could simply output the class' name, using println.
  7. Compile and execute the Gamer class. Did it work? Why?
  8. Execute the Game class (the first class you wrote). Did it work? Why?
  9. Change the name of the method main to maine in the Game class. Compile and execute. Did it work? Why?
  10. Change the name of the method back to main. Change the main methods's access modifier public to private in the Game class. Compile and execute. Did it work? Why?
  11. Make the main method, in the Game class, public again. Compile and execute. Did it work? Why?
  12. Ok, one more time. Let's rename the method main to maine in the Game class. In the main method of the Gamer class we want to invoke the maine method in the Game class. You can do it like this:
     
    package org.gamefactory.textgame;
    
    public class Gamer{
    
      public static void main(String[] args) {
          Game.maine(null); // using a class in the same package works without import!
          System.out.println("Gamer");
      }
            
    }
    
  13. Change the name of the maine back to main. Compile both classes and execute the Gamer class. Did it work? Why?

Solutions to Starting point of a program

Expand using link to the right to see the full content.

  1. The class could look something like this:
    package org.gamefactory.textgame;
    
    public class Game{
    
    }
    
  2. It compiles but will not execute. It compiles because it is a valid Java class but fails to execute since the class does not contain a valid main method.
  3. The class could now look something like this:
    package org.gamefactory.textgame;
    
    public class Game{
    
      public static void main(String[] args) {
          System.out.println("Game");
      }
    
    }
    
  4. It both compiles and executes. It can be executed since it has a valid main method.
  5. The class could look something like this:
    package org.gamefactory.textgame;
    
    public class Gamer{
    
    }
    
  6. The class could now look something like this:
    package org.gamefactory.textgame;
    
    public class Gamer{
    
      public static void main(String[] args) {
          System.out.println("Gamer");
      }
    
    }
    
  7. It both compiles and executes. It can be executed since it has a valid main method.
  8. It worked now as it worked before. Nothing has changed so why shouldn't it work.
  9. Changing the name to maine does not satisfy the requirements Java sets on a main method so, although the class compiles fine, the class can't be executed.
  10. Changing the access modifier to private does not satisfy the requirements Java sets on a main method so, although the class compiles fine, the class can't be executed.
  11. Now it compiles and can be executed again, since the class is valid Java and the main method satisfies the requirements.
  12. The Game and Gamer classes compile. Game class executes fine. We can see that the Gamer class can invoke the maine method in the Game class.
  13. The Game class compiles and executes fine. The Gamer class will not compile since it invokes a method (maine) that does not exist (any more) in the Game class.


Comments and documentation

Imagine going back to classes you wrote some years ago. Or image reading someone else's classes. It is sometimes hard to understand what the class does, or at least intends to do. Java provides an easy way to write comments, which is text not considered as code and therefore ignored by the compiler. There are two ways to write comments in your code.

There is a format way you can use when writing comments with which you can create manuals for classes and packages. See Javadoc.

single line

You start a single line comment like this.

 
// This is a single line comment

Using "//" makes the compiler ignore everything after (and including) the "//". So the comment "This is a single line comment" is ignored.

Let's illustrate this in a class:

 
package org.commenteers;

public class Example{ // Compier ignores this                                   

    // main method, starting point                                              
    public static void main(String[] args) {
        // Print a welcome message                                              
        System.out.println("Welcome to the example class ... ");
    }

}

multi line

You start a multi line comment like this.

 
/*

and end it like this:

 
*/

A multi line comment looks like this:

 
/* 
  This is a multi line comment
   ... bla bla
*/

Using "/*" and "*/" makes the compiler ignore everything between (and including). So the comment "This is a multi line comment ... bla bla" is ignored by the compiler.

Let's illustrate this in a class:

 
package org.commenteers;

/*                                                                              
  This class is just a simple example                                           
  on how to comment code in Java                                                
                                                                                
 */

public class Example{ // Compier ignores this                                   

    // main method, starting point                                              
    public static void main(String[] args) {
        // Print a welcome message                                              
        System.out.println("Welcome to the example class ... ");
    }

}


Exercises

  1. Create a file like the one below (note that the file is in a package and you need to crate (and use) a corresponding directory structure).
     
    package org.commenteers;
    
    public class Simple{
    
      public static void main(String[] args) {
            System.out.println("Simple class to test comments");
    
            for (int i=0; i<10; i++) {
                System.out.println("  i: " + i);
            }
      }
    
    }
    
  2. Write a comment before the main method saying "This is the main method".
  3. Change the class so that the first println statement is ignored by the compiler. Use single line comment to achieve this.
  4. Write an introduction text to the class using multi line comments.
  5. Change the class so that the for loop is not executed (enclose it in a multi line comment)

Solutions to - Comments and documentation

Expand using link to the right to see the full content.

  1. Just create it in the correct directory structure!
  2. Suggestion:
     
    package org.commenteers;
    
    public class Simple{
    
      // This is the main method
      public static void main(String[] args) {
        System.out.println("Simple class to test comments");
    
        for (int i=0; i<10; i++) {
          System.out.println("  i: " + i);
        }
      }
    }
    
  3. Suggestion:
     
    package org.commenteers;
    
    public class Simple{
    
      // This is the main method
      public static void main(String[] args) {
        //System.out.println("Simple class to test comments");
    
        for (int i=0; i<10; i++) {
          System.out.println("  i: " + i);
        }
      }
    }
    
  4. Suggestion:
     
    package org.commenteers;
    
    /*
     *
     * This class is something the authors forced us to work with
     * The class really does nothing useful and all we'll ever get
     * out of it is how to comment things... but, hey that's kind of useful!
    */
    
    public class Simple{
    
      // This is the main method
      public static void main(String[] args) {
        //System.out.println("Simple class to test comments");
    
        for (int i=0; i<10; i++) {
          System.out.println("  i: " + i);
        }
      }
    }
    
  5. Suggestion:
     
    package org.commenteers;
    
    /*
     *
     * This class is something the authors forced us to work with
     * The class really does nothing useful and all we'll ever get
     * out of it is how to comment things... but, hey that's kind of useful!
    */
    
    public class Simple{
    
      // This is the main method
      public static void main(String[] args) {
        //System.out.println("Simple class to test comments");
    
        /*
        for (int i=0; i<10; i++) {
          System.out.println("  i: " + i);
        }
        */
      }
    }
    

Chapter Links

External links

Books this chapter is a part of

Programming with Java book

Book TOC | previous chapter | next chapter