Java Keywords (Part I): Creating Classes

I think it is important for every beginner-level developer to fully understand the proper usage of keywords of any language. I will write a multi-part series outlining all Java keywords (as of Java 8), providing an explanation regarding it usage (or multiple usages), and illustrate this with simple examples. So, without further ado, lets examine this topic. The Java language contains 50 keywords of which only 48 are used. The following is a list of all the keywords in the Java programming language.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.
Although the list above is arranged in alphabetical order, I will go through them in a different order.

Access Modifier Keywords

Java 3 keyword that are used to control the level of access to classes, variables, and methods. Those keywords are: public, protected, and private. The easiest two to understand are "public" and "private" so I will start with those two.

public

The keyword "public" means that the class, variable, or method tagged with this keyword is accessible by any class in your program or by any other program that interacts with the declaring class. Sounds confusing? Consider this example:

public class MyClass {...}

public class YourClass {...}
Because both classes are tagged as "public", they can "see" each other; even if they are not necessarily part of the same application. Therefore, my program can have access to "YourClass" and your program can have access to "MyClass". This is very convenient for program to take advantage of features already included in another program (there is no need to reinvent the wheel).

public class MyClass {...}

public class YourClass
{
    public void printHelloWorld()
    {
        System.out.println("Hello World!");
    }
}
Suppose your class implemented a method where "Hello World!" is printed out to the console (screen). If my class needs a similar method to be implemented, I can add a method to it that does the same thing or I can reuse the "printHelloWorld" method in your class; assuming my class has access to it. I will show how this in a future blog discussing methods; how to write them and how to use them. All you need to know at this moment is that the using the keyword "public" in classes, variables, and methods makes them accessible from anywhere. In academic problems, you will most likely tag all of your outer classes, and often all your methods, as "public". In real-world applications, you want to limit the scope (accessibility) of your classes, variables, and methods to the lowest possible level. This means you want to grant the lowest level of access required for classes and applications to collaborate with each other. For now, let just say that all classes, variables, and methods MIGHT need to be accessible in some way.

private

This is probably the easiest keyword to understand. Private means that it is for your eyes only. Whatever that private thing is, it is not something you share. And if you do decide to share something private, you decide who you share that private thing with. And that is exactly what the "private" keyword means. For obvious reasons, an outer class cannot be private (otherwise, why create it in the first place?). The image below shows the "New Class" dialog in Eclipse. Notice the area being surrounded by the hollow red square. The section is labeled "Modifiers". The access modifiers are on the top row and are selected by clicking on radio buttons. Out of the four listed, only two can be selected: "public" and "default" (which has not been discussed yet). The keyword "private" is grayed out because the Java language specification does not allow that keyword to be used in a class declaration. "Class declaration" has not been discussed either, but you might already know what that means.

public class MyClass {...}

public class YourClass
{
    private void printHelloWorld()
    {
        System.out.println("Hello World!");
    }
}
In this case, even though your class is public, and thus can be accessible from anywhere, the method "printHelloWorld" is only visible by your class. No one else has access to this method because it is private.

A few paragraphs back, you learned the term "outer classes". If you implied that there must be such a thing as an "internal" class, you implied correctly. The correct term for that is "Nested Classes" and they come in multiple forms. For now, I will only discuss "non-static nested classes" in a subsequent section.

protected

Usage of the "protected" keyword is limited to variables and methods. Variables and methods tagged as "protected" are only accessible to children classes of the declaring class. Class hierarchy will be discussed at a later time. At that point, usage of this keyword will be illustrated with code examples.

no modifier

This is the fourth and last access modifier in the Java language. This is a unique case because there is no keyword for "default" access. Classes, variables, and methods lacking a access modification keyword have said to have default access. Default access is limited to classes located in the same folder where the declaring class resides. In Java, folders are known as packages and package is another keyword that will be discussed later. Packages will be discussed at a later time. At that point, usage of this keyword will be illustrated with code examples.

Another name for default access modification is "package-private", meaning that a class, variable, or method with default access is consider as "private" outside the containing package. Lastly, do not mistake "default" access with the default keyword. This keyword has two functions which have nothing to do with access modification. Both of these usages will be discussed at a later time.

Class Declaration

class


public class MyClass {...}
The statement above is the class declaration for my class. Some people might refer to this as the class header. A class declaration MIGHT be preceded by an access modifier. Remember that not including an access modifier will default to "default" access modification. In the example above, public is the access modifier for this class declaration. The access modifier is immediately followed by the "class" keyword. The purpose of the keyword is to tell the Java compiler that the unit of code enclosed in curly braces "{ }" define the scope of the class known by the name that immediately follows the keyword. In this example, the name for this class is "MyClass". The name of the class is also used to identify the Reference Type for objects created with this class. Reference types are discussed in my Data Types article.

A class declaration can have more components to it. This is the simplest form of a class declaration which for now should suffice. More complex forms of class declaration will be introduced when applicable topics are discussed.

Nested Classes

A nested class is a class that is contained by another (outer) class.

public class MyOuterClass
{
    // variable and methods omitted

    private class MyNestedClass
    {
        // variable and method omitted
    }
}
Like in the case of variable and methods of a class, a nested class declared as "private" cannot be accessed by anyone other than the containing class. In this example "MyNestedClass" is only visible to "MyOuterClass". Variables, methods, and nested classes are generally known as "members" of the containing class. No member can be accessed beyond the access level of the outside class. So, if an outer class is "package-private" no other class outside the package will have access to its members, even if these members are tagged as public. This should be common sense but it can be confusing. So, think of it this way, if you cannot access a house, how could you access the rooms of that house? The same logic applies here.

class MyOuterClass
{
    // variable and methods omitted

    public class MyNestedClass
    {
        // variable and method omitted
    }
}
"MyOuterClass" above is "package-private" because it has default access modification. Therefore, the class itself is not visible outside the containing package. All accessible members of my outer class are restricted to the package as well. Therefore, "MyNestedClass" is also package-private regardless of the "public" access modifier in the class declaration.

Summary

In this post, I listed all 50 Java keywords, introduced all four access modifiers provided by the Java language, and discussed the simplest form of class declaration. With that, I also introduced the concept of non-static nested classes in order to supplement the topic of access modification. The following table summarizes access modifiers in Java

Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no-modifier Y Y N N
private Y N N N

Comments

  1. The Java library contains vital and useful information to perform internal operations. Understanding the special meaning of each reserved word will provide endless opportunities in creating a program that will impact our society for the greater good. Understanding the differences between private, default (no-modifier), protected, and public modifiers are important because they specify how classes and class members are accessed.

    ReplyDelete

Post a Comment

Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

The Beauty of the Null Object Pattern