Broad Network


Java Class and Object Overview

Java Object Oriented Programming Core – Part 1

Forward: In this part of the series, I give you an overview of Java classes and objects.

By: Chrysanthus Date Published: 3 Sep 2012

Introduction

Once again, welcome to the exciting world of Java programming. This is the third series of the Java professional programming course. A Java program is the interaction of objects. You will see the core of all that in this series. Remember, in theory, you can learn Java as your only programming language as it is used almost everywhere. The voyage (learning process) we started, must continue.

In this part of the series, I give you an overview of Java classes and objects. If you have been covering the volume in the order given from the web page titled Java Course, then you should already be familiar with Java Classes and instantiated objects. In this part of the series, I give you a formal overview of classes and objects. Also, in this series and for the rest of the volume I will be using most of the vocabulary that Java expects us to use.

Object Oriented Programming is abbreviated to OOP. A strict OOP program (application) is the interaction of program objects.

Prerequisite
In order to understand this series, you should have covered the series, whose first parts are titled,
- Getting Started with Java
- Java Data Types

in the order given. To arrive at any of the series, just type the title and my name, Chrys, in the search box of this page and click Search.

Dictionary Meaning of a Class
In a dictionary, a class has a number of meanings. In the Oxford dictionary, there are two meanings that concern us. One of the meanings is:

A class is a category of people, animals or things that are grouped together, especially because they have similar characteristics or qualities.

In life you can have a class and a subclass (even sub-subclass). So the other meaning in the dictionary that concerns us is:

A class is each of the several different levels of comfort, available to travelers in a train, plane, bus, etc: first class, tourist class, second class. You can even have third class.  

In this part of the series, it is the first meaning above that I will deal with. I give a real life example of the first meaning: A blueprint is the design of a house on paper. So far as Java is concerned, the house on paper, is a class. The physical house is built on land following the design in the blueprint. From the same blueprint, many other physical houses of the same structure and color can be built. So far as Java is concerned, each physical house is an object. So, in Java, a class is likened to a blueprint and objects created from the class are likened to the physical houses. So far as Java is concerned, when you create a house from a blueprint, you are instantiating the blueprint (class), and each physical house is an instance of the class (blueprint).

The second dictionary meaning of class above will be applied to Java in a different part of the series, where I will talk about a Java class feature called, Inheritance. That meaning does not apply to this part of the series.

Class and Instantiated Object in Java
In a Java program, a class is a piece of code, which you can see. An object instantiated from the class resides in the computer memory, and you cannot see the code. You can however access the object using the object’s variable, and other object features that you can type. Most of the time, you use the instantiated objects of a class to carry out tasks and not the class itself.

In simple terms, the syntax to produce a class is:

    class Classname
        {
            //properties
            //methods
        }

A property is a characteristic of the class. A method is an action of the class. Java prefers to call a property, a field; but in my opinion, property, is a better word. In the class code, a property is a statement and a method is a small construct (large statement).

In simple terms, the syntax to instantiate a class into an object is:

    ClassName objectName = new Classname(arguments);

The word, new, is an operator.

The statement can be broken down into two statements, which are:

    ClassName objectName;
    objectName = new Classname(arguments);

The second statement here can be typed after zero or more statements below, in the code. The first statement here is a declaration; the second is the actual instantiation. Before, declaration and instantiation are combined in one statement.

Difference Between Primitive Objects and Instantiated Objects
A primitive object or data type, is a simple object like an int and has no method. A mature or non-primitive object is an instantiated class object, and can have one or more methods.

A Class and Object Example in a Program
Read and try the following code, which is of a very simple calculator:

class Calculator
    {
        int num1;
        int num2;

        int add()
            {
                int sum = num1 + num2;
                return sum;
            }
    }

class Machine
    {
        public static void main(String[] args)
            {
                Calculator obj1 = new Calculator();
                Calculator obj2 = new Calculator();

                obj1.num1 = 2;
                obj1.num2 = 3;

                obj2.num1 = 4;
                obj2.num2 = 5;

                int result1 = obj1.add();
                int result2 = obj2.add();

                System.out.println(result1);
                System.out.println(result2);
            }
    }

There are two classes above, the main class that has the main method and the class of interest called, Calculator. The class of interest has two properties (num1 and num2) and one method called, add(). The method adds the values of the two properties and returns the sum (total). In the class, Calculator, we have the two variables un-initialized; we also have the add() method. Since the variables are not initialized, it will be possible to create objects from the class, each with its own pair of numbers, and each object will add its own pair of numbers. Note that the method in the Calculator class does not have parameters (does not take arguments). Also note that the property names (variables) are used in the addition statement of the add() method.

You describe a class beginning with the reserved word, class. Then you have a space and then follow it with the name of the class. You choose whatever name you want to give for the class. Inside the class, you have properties and/or methods.

The names of the classes in the program are, Calculator and Machine. Machine is the name of the main class. The first two statements in the main class create (instantiates) two objects with the names, obj1 and obj2. A statement to instantiate an object uses the operator (reserved word), new. On the extreme left and right of the assignment operator you have the name of the class. The class name on the right has parentheses.

The next two statements assign values to the properties of the object, obj1; To assign or change the value of a property, you begin with the name of the object, then a dot and then the variable name of the property. That is followed by the assignment operator and then the value for the property. Do not forget to end any statement with a semicolon. The two statements that follow, give values for the same properties for the second object, obj2.

Note that we now have two objects, each with its own pair of numbers (property values). The next two statements that follow in the main method call the add() method for each object. Remember, an object has all the properties and methods of the class. However, you do not see the code of any object as you see for the class. The return values of the method calls are assigned to new variables. The last two statements display the results, using the new variables.

A class groups corresponding variables and method(s) properly together, as in the above case. Read through the program again to appreciate what has really happened.

Under normal circumstances, you declare the properties in a class without initialization. That is why in the above class, num1 and num2 do not have any values assigned to them. There is what is called, constructor method, that can be used to assign initial values to them, as an object is being created (instantiated) from a class (see below).

Creating an Object from the Class without Constructor Method
A class like the one above (Calculator) does not have a constructor method (see below). When a class does not have a constructor method, you create an object from it just as you create a Java array, but instead of square brackets you have parentheses, and only for the right-hand class name.

To declare (start creation of) an object without constructor method, you begin with a class name, then a space, then a variable name that you choose to identify the object; then a semicolon to form a statement; as in:

    Calculator obj1;

This is similar to the declaration of the following int:

    int  myInt;

Now you have the name of the object and it is of type, Calculator. You can then assign the actual substantiated object as in:

    obj1 = new Calculator();

This is similar to assigning a value to a declared int type as in:

    myInt = 5;

You can combine the two statements in one as in:

    Calculator obj1 = new Calculator();

just as you can combine the two int statements as:

    int  myInt = 5;

Using an Object
The aim of our class and objects is to solve the same kind of problem. It is to add two numbers of two variables. Everything being equal, you cannot use a class; you use but objects created from the class. Members (properties and methods) of a class automatically become members of the instantiated object. You can create many objects from a class; the main thing you need is different variable names for different objects. To access a member of an object, you begin with the name of the object. This is followed by a dot, and then the variable (property or method name) of the object. If the member is a method then you will follow the method variable name with parentheses. These parentheses may have arguments, if the declaration of the method had parameters.

To solve our problem, we need to assign values to the properties (num1 and num2). This is what the second and third code segments in the main method above do. An object will not just solve your problem by itself. An object normally has one or more methods that you call to accomplish a particular task, using one or more properties of the object. The add() method of our objects, do the addition using the two properties of the object; because of the way we declared (described) the method. The fourth code segment in the main method calls the add methods (one method per object) and assigns the return values to new int primitive object variables, result1 and result2. The fifth code segment of the main method displays the results.

The Constructor Method
If you want to create an object and at the same time initialize (assign values to) the properties, then you need to declare what is called a constructor method as you type the class. The constructor method is simply called, constructor. After this, to instantiate (create) an object from the class, you have to use the constructor method call. The following code illustrates this.

class Calculator
    {
        int num1;
        int num2;

        Calculator(int ident1, int ident2)
            {//constructor method
                num1 = ident1;
                num2 = ident2;
            }

        int add()
            {
                int sum = num1 + num2;
                return sum;
            }
    }


class Machine2
    {
        public static void main(String[] args)
            {
                Calculator obj1 = new Calculator(2,3);
                Calculator obj2;
                obj2 = new Calculator(4,5);

                int result1 = obj1.add();
                int result2 = obj2.add();

                System.out.println(result1);
                System.out.println(result2);
            }
    }

The constructor method, in the non-main class, has the same name as the non-main class. The content of the constructor method is usually initialization of one or more or all the properties of the class. The values to use in initialization come as arguments to the constructor method. That is why a constructor method description has parameters. With the presence of the constructor method, everything being equal, you do not need to assign a value to a property of an instantiated object, since the constructor method does that for you during instantiation. The constructor method is called by you, during object instantiation (object creation).

When instantiating an object, you send the values for initialization as arguments, as in:

    Calculator obj1 = new Calculator(2,3);

Or as in the code segment:

    Calculator obj2;
    obj2 = new Calculator(4,5);

In this cases, the word, Calculator and its parentheses, is the call. Note that the arguments have been typed in the parentheses of the right hand class name. Here, the right hand class is a method call; remember, the constructor has the same name as the class.

Read the above program again to appreciate the role of the constructor method; also note that with the constructor method, there is no need for the instantiated object properties to be assigned values.

The Default Constructor
If you do not declare a constructor for a class, Java provides you with a default constructor unknown to you. The first class program above, is an example with the default constructor. During instantiation with the default constructor, the name of the constructor is the name of the class, with parentheses, but without arguments. The first line in the main method of the program illustrates this. Note: whether you are dealing with the default constructor or not, the name of the constructor is the name of the class. Since it is a method, during instantiation of the object, it has parentheses, which might be empty.

Syntax to access Object Members
The phrase, “class member” or “object member” can be used for properties and methods of a class or object, respectively. Remember, everything being equal, you use objects, not classes. You create an object from a class. The syntax to access a member of an object is:

    objectName.member

If the member is a method, then you need to follow this up with parentheses. In this tutorial, apart from the constructor method, we have not used any method with arguments, but methods can have arguments; in the typing of the class declaration, such methods would have parameters.

Default Values
If you do not want to use a constructor, you can type the properties of the class, initialized. In that way, the values you give for the class properties, are the default values. For any instantiated object, the values will still be there. Read and try the following code:

class Calculator
    {
        int num1 = 2;
        int num2 = 3;

        int add()
            {
                int sum = num1 + num2;
                return sum;
            }
    }

class Machine3
    {
        public static void main(String[] args)
            {
                Calculator obj1 = new Calculator();
                int result1 = obj1.add();

                System.out.println(result1);
            }
    }

Using default values may not be good practice.

Before we leave this part of the series, know that a class can have many methods. One of the classes above has two methods, which are the constructor method and the add() method. You type methods, just one following the other. Remember, the constructor method has the same name as the class and does not have a return type.

Also remember that the instantiated class is the instant of the class. There can be many instances of the same class.

Well, this tutorial has been a long ride; we take a break here and continue in the next part of the series.

Chrys
NEXT

Related Articles

Java Course

Comments

Become the Writer's Fan
Send the Writer a Message