Java OOP Basics
Java Basics – Part 16
Forward: In this part of the series, I give you the basics of Java Object Oriented Programming.
By: Chrysanthus Date Published: 2 Sep 2012
Introduction
When you have a set of variables and methods that work together and would appear in many parts of your code, you can put all that in one generalized unit called a class. There will be no need for repeat typing of the set. In this tutorial, I am talking about a set of variables and methods. In one of the previous tutorials, I talked about a set of statements that forms a method. Here, I am talking about a set of variables and methods that form a class. The methods work with the values of the variables. Under that condition, it is possible that the values of the variables and the results of the accompanying methods can be changing. In order to use the class, you have to create a particular entity from the class, everything being equal. That particular entity is called an object. In this part of the series, I give you the basic explanation of Java classes and objects.
In fact Java programming is essentially OOP. In other languages like C++ you can separate variables from methods (functions), separate variables from one another, separate methods from one another, so that the variables can work (exist) independently, methods can work (exist) independently, and variables and methods can work (exist) independently. In Java you do not do that. In Java, variables without methods should exist together in a class; methods without variables should exist together in a class; variables and methods should exist together in a class. In Java variables should not exist independently from one another, methods should not exist independently from one another. In Java, if variables are to exist, they exist together in a class, or they exist with methods in a class. In Java, if methods are to exist, they exist together in a class or they exist with variables in a class. Of course, you can have many classes in one program
Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.
Let us consider a group of variables and methods that would work together as a generalized unit. Read and try the following code and note that it returns the sum of 2 and 3.
class ClassJustForMethod
{
int add(int no1, int no2)
{
int sum = no1 + no2;
return sum;
}
}
class MainClass1
{
public static void main(String[] args)
{
ClassJustForMethod addObj = new ClassJustForMethod();
int num1 = 2;
int num2 = 3;
int result = addObj.add(num1, num2);
System.out.println(result);
}
}
There are two classes in this code, but that is not the way a Java program should be written. Before I explain how the Java program should have been written, let me first of all explain how the code works to add the two numbers.
The next statement calls the add method of the other class. This add method adds the two integers initialized. The last statement displays the result of the addition.
The other class in the program is, ClassJustForMethod. This class has only the add method to add two integers.
Now the above code (program) sums just two numbers, which are 2 and 3. You would want a piece of code that sums any two numbers, not just 2 and 3. One possibility is to include another method that would receive the two numbers, assigned the values to the two variables, num1 and num2, then call the add(no1, no2) method. There is another possibility, which is to collect all the relevant statements and place into the non-main class, then create an object from the class that would add any two particular numbers. A class is a generalized unit of code, from which things call objects can be created to do particular task. An object is called the Instance of a class. Note: in the above code the two initialization statements for num1 and num2 and the method (add), work together. That is why it is advisable to have the two initialization statements and the method in one unit called a class.
A class is a generalized unit from which objects can be instantiated (created). A class is basically a code unit that has variables and/or methods that work (exist) together. The variables are called properties. A class itself cannot solve a problem; that is, a class itself cannot carry out a task. It is an object created from a class that carries out a task; not the class.
There is a nuance here. You have objects of the primitive data types and you have objects created from a class. The context in this tutorial should tell you the kind of object I am referring to. The whole number, 5 in a field is a primitive object of the int type; so int is a primitive class; likewise double is a primitive class.
When you create an object from a class, we say you are instantiating the object. An object created from a class has the same properties and methods as the class. For the above code you can create many objects, each with its own pair of numbers. With this, each object can go ahead to add its own pair of numbers; that is a convenience and not an inconvenience as you might be thinking (see illustration below).
In fact from the beginning of this tutorial I have been using classes. I have been using principally the main class, which must be in any Java program. Along the lined I used more than one class and instantiated objects. In this part of the series, I address the issue of classes and objects formally; and from here I will be teaching you Java in terms of classes and objects, as Java should be.
A Class and Object created from the above Code
The above code can be converted into a class and two objects as follows (the non-main class has been renamed):
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);
}
}
What do we want for the non-main class? We want two variables (called, class properties) to work with the add() method. In the class, Calculator, we have the two variables un-initialized, and the add() method, above. 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 the 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 define 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 are now, 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.
The variables and the method we had in the first program are the same variables now called properties and the same method, mainly present in the non-main class. Corresponding variables and method(s) are now properly grouped together. Read through the second 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).
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. The creation (instantiation) is also similar to the creation of primitive object (data) types (as explained below).
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 problem, which the first program above still solved. It is to add two numbers of two variables. 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) 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 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 defined (described) the method. The fourth code segment in the main method calls the add methods and assigns the return value to new int primitive objects variables by result1 and result2. The fifth code segment of the main method displays the results.
If you want to create an object and at the same time initialize (assign values to) the properties, then you need to define 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 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 define a constructor for a class, Java provides you with a default constructor unknown to you. The first class program (second 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 above, but methods can have arguments; in the typing of the class definition, the 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, 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 is not good practice.
There is more to Classes than I have given. Note: in Java, programming is the interaction of objects. So, you will see more as we go along in the course. Time to take a break. We continue in the next part of the series.
Chrys