JAVA CLASSES


Contents


Fields, Methods, and Access Levels

  • Java classes contain fields and methods. A field is like a C++ data member, and a method is like a C++ member function.

  • Each field and method has an access level:
  • Similarly, each class has one of two possible access levels: Note: for both fields and classes, package access is the default, and is used when no access is specified.

    Simple Example Class

    Here's a (partial) example class; a List is an ordered collection of items of any type:

    
    class List {
        // fields
            private Object [] items;    // store the items in an array
            private int       numItems; // the current # of items in the list
        
        // methods
            // constructor function
            public List()
            {
                items = new Object[10];
    	    numItems = 0;
            }
    	
    	// AddToEnd: add a given item to the end of the list
    	public void AddToEnd(Object ob)
    	{ ... }
    }
    
    
    Notes

    Static Fields and Methods

  • Fields and methods can be declared static (this is true in C++, too). If a field is static, there is only one copy for the entire class, rather than one copy for each instance of the class. (In fact, there is a copy of the field even if there are no instances of the class.) For example, we could add the following field to the List class: And the following statement to the List constructor: Now every time a new List object is created, the numLists variable is incremented; so it maintains a count of the total number of Lists created during program execution. Every instance of a List could access this variable (could both read it and write into it), and they would all be accessing the same variable, not their own individual copies.

    A method should be made static when it does not access any of the non-static fields of the class, and does not call any non-static methods. (In fact, a static method cannot access non-static fields or call non-static methods.) Methods that would be "free" functions in C++ (i.e., not members of any class) should be static methods in Java. Also, methods that are logically associated with a particular class, but that only manipulate the class's static fields should be static. For example, if we wanted a function to print the current value of the numLists field defined above, that function should be defined as a static method of the List class.

    A public static field or method can be accessed from outside the class using either the usual notation:

    or using the class name instead of the name of the class object: For example, if the numLists field is public, and there is a variable L of type List, the numLists field can be accessed using either L.numLists or List.numLists. Similarly, if the List class includes a public static method PrintNumLists, then the method can be called using either L.PrintNumLists() or List.PrintNumLists().

    The preferred way to access a static field or a static method is using the class name (not using a class object). This is because it makes it clear that the field or method being accessed is static.

    Final Fields and Methods

  • Fields and methods can also be declared final. A final method cannot be overridden in a subclass. A final field is like a constant: once it has been given a value, it cannot be assigned to again. For example, the constructor function for the List class initializes the "items" field to (point to) an array of size 10. It would probably be better to use a constant for the initial size of the array. Only a single copy of the constant is needed for the whole class, not one for every class instance, so it would be appropriate to make the field static as well as final: The assignment statement in the constructor function would change to:
    TEST YOURSELF #1

    Consider the program defined below.

    Question 1: Which of the following is true?

    Question 2: Which of the following correctly describes what happens when the program is compiled and run?

    solution


    Some Useful Built-in Classes

    Note: These classes are not really part of the language; they are provided in the package java.lang. You can get more information on-line via the Java Packages page.

    String

    Object

    Boolean, Integer, Double, etc


    TEST YOURSELF #2

    Question 1: Consider the following program.

    The person who wrote this program expected the output to be: n = 6; m = 5. However, the actual output is: n = 5; m = 6. Explain why.

    Question 2: Consider the following function. This function was intended to create and return a string that is the reverse of its parameter. (For example, if parameter S = "hello", the function should return "olleh".) However, there are several problems with the function as written.

    First, identify each problem (write the bad code and give a brief explanation of why it is incorrect). Then give a new, correct version of function Reverse.

    solution


    Solutions to Self-Study Questions

    Test Yourself #1

    Test Yourself #2