5.2 - An Example Java Class

An Example Java Class

We have illustrated a very simple application previously to display "Hello World!". Here is an application that extends the previous Java application to include states and methods and to show how they can be invoked from within the main() method.

 3   //An example class and application
 5   import java.lang.*;  1
 7   public class TestClass extends Object 2
 8   {
 9     private int x, y=5; 3
11     public TestClass(int z) 4
12     {
13       x = z;
14     }
16     public void display() 
17     {
18       System.out.println("The values of (x,y) are: (" + x + "," + y +")"); 5
19     }
21     public static void main(String args[]) 6
22     {
23 	  TestClass test = new TestClass(10); 7
24 	  test.display(); 8
25     }
26   }

The full source code for this example is here - TestClass.java.


The import keyord is like the include keyword in C++. It allows the programmer to choose classes that are accessible from this class.


The extends keyword in Java allows the programmer to define the parent class. In this case we are choosing the Object class - do not think about that! just ignore it for the moment.


The states of the class are usually modified to be private to the class (the default access modifier is not private - we will discuss this later). You can assign initial values to the states. Variables of the int type are initialised to 0, if no initial value is supplied. As previously discussed in C++, this facility does not remove the need for constructors.


The TestClass() is the constructor of the TestClass class. This method must have the same name as the class name and it cannot have a return type - just like C++.


The System.out.println() method is the equivalent of the cout stream that we had in C++. We can use the + operator to concatenate strings or even variables of the standard types (in this case int).


The main() method is written inside a class (all methods must be inside classes, there are no global methods in Java). It is static, as it is associated with the class and not the object, otherwise which main() method would be chosen from the 1000's of possible TestClass objects? The main() accepts an array of String objects as arguments to the application from the DOS command prompt/Unix shell/etc.


To create an object in Java, you must use the new keyword. When the code TestClass test is written, this creates a reference test of the TestClass class. The new TestClass(); creates the object by calling the constructor. This is then assigned to the reference using the = operator.


The display() method is called on the test object, in the same way that we called methods on objects in C++.

These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way.
Derek Molloy,
6 Nov 2013, 15:44