Wednesday, July 27, 2016

Java - What is Class, Object, Attributes and Methods ?

Java is an OOP language - Object Oriented Programming Language.

To understand the concept of OOP,
we need to understand the concepts of Class, Object, Attributes and Methods.
These concepts form the base and structure of a Java program.

In fact, we deal with these concepts in our daily life.
In daily life, we deal with various objects like fridge, car, pen etc.

These objects have
attributes like color, size, make and
methods of functioning regarding what we do with them and what we do to them.

For example,
A pen has attributes like color, shape, make and method of functioning/operating
such as removing the cap or pressing a button to write with it

Further,

When we simply say a pen, it means any pen belonging to class of pens.
Only when we specify attributes like ownership, make, model, color etc, it refers to a particular pen - an object,

So, the concepts of Class, Object, Attributes and Methods are real life concepts.

In OOP the same concepts are adapted to software entities.
Take example of software entity ‘Employee’.
Here,
An employee has
attributes like name, age, designation etc. and
methods for  calculating allowances, deductions etc.

We can say,
An employee in general is a class with certain attributes and methods.
A particular employee exhibiting particular attributes and methods is an Object belonging to that Class.

Java as an OOP programming language treats software entities as class and objects as explained above.

In the model of POP (Procedure Oriented Programming Language) like COBOL,
Employee Data and Procedures acting on Data are treated separately.
Whereas, in OOP language like Java, Data (Attributes) and Procedures(Methods) are
clubbed together and treated as an Employee Object. 

Then,
the application with many such objects becomes interaction between Objects rather than various procedures acting on various data.

Now, we will go through these concepts by constructing a Java class from a simple data entry form.

Let us assume an educational institute is accepting application forms from students for admission.

Shown below is the blue print of the STUDENT APPLICATION FORM.


The blue print of a form has some data fields and also fields (Total, Average) with computational procedures.

Now, as procedure of admission,
Each student would be given a copy of the above blue print, that he would fill with detail and submit it for consideration as shown below.


The above picture identifies the equivalents in terms Java.
We can see

Manual                                                                                      Java

Blueprint                                                                            Class
Copy of the blueprint to be filled with detail                     Object
Data Fields                                                                       Attributes
Computational Procedures                                              Methods

In the example of student admission form –

Java Class is Blue print of the Student Application.
Object is copy of the blueprint with particular values assigned to the attributes.
Attributes are data fields Name, Address, Course Selected, Maths, Science and Humanities 
Methods are procedures Total Marks and Average.

Note that Class is only a blueprint of an object, not an object itself.

Now,
We will convert manual blue print and copy into  class and object in Java language. 

We will start with empty blue print and create its class equivalent in Java language step by step.

Step-1
  

  Line 1 – Class AppForm{

The keyword ‘class’ declares ‘AppForm’ as a class.

Any meaningful name can be given to the class provided they follow naming rules.

 Rules for naming.

1.     Name should begin with a letter, dollar symbol ($) or underscore symbol (_).
             ,can be followed by letters, digits,$ and _.
       2.     Reserved words are not allowed (e.g. ‘class’ is a reserved word )
       3.     No duplicate variable names 

The braces “{“and “}” indicates beginning and ending of a class and contain body of the class within it.
Everything related to the class (Attributes and Methods) should be written within these braces.

These braces are used in Java to indicate beginning and ending of a block in general.

Step-2

We have declared a class.
In this step, we will declare the variables present in the blue print. 

  
Naming the variables must follow the naming rules as mentioned above.

Variables can be of different data types – numeric, character, Boolean etc.
Corresponding Java keyword (int, String etc) should be used to denote the type. 

Line 1 – String name, address, course;

The keyword ‘String’ declares variables name, address, course as character type.
Semi colon at the end indicates end of statement.

All Java statements end with semi colon.

Line 2 – int maths, science, humanities;

The keyword ‘int’ declares maths, science, humanities as integer type

Common Standard Data Types in Java.

Data Type            Java keyword

Integer                   byte, short, int, long
Decimal                 float, double
Character              char, string

Step-3

Now, after declaring the class and attributes,
we are coming to the last part of declaring methods.

Method is a function or subroutine that manipulates or calculates some values and returns the result to the main program.
In this example,
The method has to sum up the values of maths, science and humanities and return the total.
Let us start with basic structure of the method.

Step-1 
Int total()
{
..
..
}

A method is declared like a variable – data type followed by method name.
Difference is it will have parentheses at the end.
Parentheses indicate that it is a method, not just a variable.
In this example, its data type is ‘int’, since ‘total’ is sum of integer values maths, science and humanities.

                   Then we have open and close braces indicating beginning and ending of the method.
                   All statements belonging to the method are written within the block. 

                    Step-2 
int total()
{
total =maths + science + humanities;

}

Here, we have included the computational statement in the body.
Sum of maths, science and humanities is assigned to ‘total’.

Step-3
int total()
{
total =maths + science + humanities;
return total;
}

Here, we have added the keyword ‘return’ followed by the variable that contain the sum.
Method is a subroutine, so the result is returned to the main program.

  Note: If method is not returning a value, instead of data type, the keyword ‘void’should be used.
Then method signature would be  ‘void method_name()', no need for ‘return’ statement because no value would be returned. 

Step-4:

Now, we will add the ‘average’ method.

Similar to the ‘total’ method, we have added the method ‘average’.
Average is calculated by dividing the total obtained from ‘total’ method by 3.
‘return’ statement is used to send the result back to main program.

Note that body of each method is enclosed within their own braces.

Finally, we have translated the manual form into a Java class.
But, class is only a blue print. not an object.
Manually we have to make a copy of the blue print to fill in with data.
Similarly, we have to create a copy the class in the computer memory to fill with data, which will be called as object.
Now, we will see how to create an object from this class template.


Fig 5



Earlier, we have defined a class ‘AppForm’ – blue print.
Now, we have to create an object from ‘AppForm’.
We will name it as ‘AppFormObject’.

While making a copy from a blue print, we perform an action like photocopying.
Similarly, to create a object from ‘AppForm’, we need to perform an action.
That is, executing a statement.
Executing a statement is a procedure, so it must be present inside a method.
In Java, method or variable declaration, they must be inside a class - Java is all classes.
So, we will start with a class declaration for the object.

Step -1

Class AppFormObject {
}

The keyword class declares ‘AppFormObject’ as a class.

Step -2
Class AppFormObject {

public static void main(String() args){
...
...
}
}

As we said above, we have to perform an action to create an object from a class.
So, it must be a procedure – a method.
Therefore,
Inside the class 'AppFormObject', we add a method called ‘main’.
It is not user defined method like ‘total’ or ‘average’ but a built in one.
We have chosen this special method ‘main’ because; execution of any Java program will start from ‘main’ method only.
So,main’ method will be present in every Java program
Here, when the program is run, statements inside the ‘main’ method will be executed.
And the object will be created in the memory like we make a photocopy out of a print.

The signature of ‘main’ method is not just ‘void main()’,  it has other elements.
We need not go into detail, simple explanations is enough now.

Public – It is available to all classes
Static – Its representation cannot be altered
Void – It won’t return any value
String()args – For experienced programmers we can leave it now.

For now, one can simply copy the method signature with braces
and write the statements to be executed inside it.
.

Step-3
Class AppFormObject {

public static void main(String() args)
{
AppFom af;
af = new AppForm();

            }
}

Now we have added statements that are to be executed to create an object .

Line -1

Appform af;

The statement ‘AppForm afo’ declares variable ‘afo’ as ‘AppForm’ data type.
It is similar to declaring a variable like  ’int maths’ or ‘String name’.
The difference is ‘int’ and ‘String’ is built in data types, where as ‘AppForm’ is user defined type.

Line-2

af = new AppForm();

This statement creates the object and allocates memory.
The keyword ’new’ creates copy of 'AppForm', allocating memory and assigning it to ‘af’.
Now, 'af' object is copy of 'AppForm' with particular address and memory.

Rest is what we do with the object created, that is filling it with data.

Note - for built in data types like ‘int’ or ’String’, declaration is enough,
memory allocation is automatically done.
But for the user defined data types like ‘AppForm’, memory allocation for the variable is done through the above statement after declaration

What is shown is simple example of a class, object, attributes and methods.
For practice, one may pick up any data form or entity,identify the attributes and methods in them.
Then translate the form into Java class as we did above. 



.