All About Class and Object in Java



Say we want to design a beautiful city. For that,we need to chalk out a plan for roads,houses,shops etc in a paper. Then we will design each of these individually,say a house. The blueprint of house will say how many doors will be there,how many windows,how many floors etc.Each of these houses will have its owner details when they are built and distributed.So in the sense the houses will look a like but the details of each houses like owner,how many occupants will be there in the house, will vary.Even the interior may vary from one house to another. But the base of creating a house will be same.This is same for roads,the design will be same but the name,locality and length will be different. It is similar to create a beautiful application using java. As a pure object oriented language,everything in Java should be inside a class.Java classes are the blueprint or master plan just like a master plan of a house.we can create any number of houses from this master plan. The master plan is called class and the individual houses created from this master plan is called object.

Again say our trainer has asked for a single pager resume. The trainer also has given a set of things in a document(Like -name,technology,experience,contact number ect).In real world this document is treated as template or blueprint and each individuals when created their own resume follow the same rules with different data. In this example,we can say the class is a template of the document and each document created from this template is called object.The objects will have their own set of data.

So in general the flow of the class and object creation is something like:
define a class-->create objects form the class--->send message to the objects

Aristotle was first to begin a study of the concept of type.He spoke about "the class of fishes and the class birds".The concept that all objects while being unique ,are also part of the set of objects that have characteristics and behaviors in common was directly used in the first object oriented language(Simula-67).Its fundamental keyword class that introduces a new type into a program(class and type are often used synonymous).
A class is actually describing "a class of objects".If we create a class of birds,any object belonging t this class will share these characteristics and behaviors.



A Class:
A class is given a name(called Identifier) to distinguish from other classes of the application.The class includes physical components called member elements and number of methods for operations. It is a datatype where the class creator will define how the new type of objects looks like.The linking and bonding between data and operations on these data is known as encapsulation.In the context of behavior, in approach, parameters to the behavior and return type should be primitive data type or a class object.We can pass object and some primitive data type to a method in the form of an argument and can return an object or primitive data type.
like setValue(int xyz);
anything inside the first bracket is considered as payload to the function.It is a mechanism by which we either pass value of data or reference to the object.Certainly a class have a function with empty payload .Like
setValue();

public class MyClass{
private String firstName();
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
public String getFirstName(){
return firstName;
}
}
 
In the above statement, MyClass is an example of the structure of the class having one variable called firstName.If the constructor of the class MyClass() is called, the variable is set to the default value. In case, the constructor sets the value, it will be overridden.
Therefore every member variable will have a setter and a getter method so that the objects created from the class pass and change the values.
like setXXX(datatype value);//value passed
getXXX(){return datatype;}//method with no payload

Design of a class
While designing qualifier "-" signifies private and "+" signifies public.
like
-firstName=>String but private
+setFirstName(firstName)=> String but public

Collectively the variables and methods of a class are often referred to as members or fields of a class.
The transformation from a conceptual class diagram to class code is depicted here:
Class Diagram Class Code
MyClass -----------------------> public class MyClass
-firstName:String -----------------------> private firstName
+setFirstName(firstName:String) -----------------------> public  void setFirstName(String firstName)
{
this.firstName=firstName;
}
+getFirstName():String -----------------------> public String getFirstName()
{
return firstName;
}
so on....
the constructor is omitted here ,but in reality, we will have a constructor for a class.
Below is the general formula for a class:

<<Access specifier>> class className [extends SuperClass Name] implements interface1,interface2,....interfaceN{
//member elements mostly private
[Deceleration of member elements]
//methods mostly public
[Deceleration of methods]
}

 
Data member of a class
Data member is thing we want to communicate via its handle.It can be of any type(primitive) which is not handle.It can be a handle to an object(it must be initialized to connect it to an actual object using new in constructor).If it is a primitive data type,we can initialize it directly at the point of definition in the class.
Guidelines for class creation:

  • By convention a class name starts with a capital letter.like PrintStream
  • class is a keyword and declares that a new class definition as follows.
  • class definition in Java starts with a opening braces("{")  and ends with a closing braces.("}").
  • class contains two types of elements-Data members called fields and member functions called methods.
  • Methods in java,can be created as a part if the Class.A method can only be called for an object.Except static methods can be called for the class without an object.
Java being a single rooted language,all classes are child of Object class.

public class MyClass{..}
//is equivalent to 
public class MyClass extends java.lang.Object{...}
 
Semantically java.lang.Object class is an abstract class but syntactically it is not declared as abstract.As it is a concrete class we can create object of the Object class.
so

Object o=new Object() //is legal but not sure where to use its methods
a.methods();
 
An Object:
Instance of a class is called object .Thus ,Object and instance are interchangeable in java.In object oriented programming language, Objects can communicate between themselves using message. They know which message is for which object and how to interact with it..Message is sent to object to perform some operation.Object is having data and behaviors. The linking and bonding between data and operations on these data is known as encapsulation.(so an object is an amalgam of data and code).These data can only manipulated using these operations.In other words,objects data values are not directly accessed from outside,instead they are accessed via the object's behaviors.So an object is having some private data values and public behaviors to manipulate the data.
Construction of an Object

MyClass mc=new MyClass();
 
where Myclass- is the provider class,
mc is the object reference of the MyClass,
new creates the instance of the provider class,
MyClass() is the constrcutor of the provider class.This is the default constructor or can be overloaded constructor.
The user class or object is only bothered as the methods exposed by the provider class.It does not know anything about the implementation of the method.So an object of a provider class implements the details of what a method does.Provider class only knows how the method is implemented.
Now to call a method provide by the provider class, we need to use the dot operator to gain access to the provider class's field if they are public.
like

mc.setFirstName("Joghn");
//or
String name=mc.getFirstName();
 

for function with a payload or argument to understand the process better ,lets start from right to left. we pass an argument called Joghn(string) to the method setFirstName.And call this method on the instance of the provider class -MyClass using a .(dot) operator to identify the specific object (stored in the memory) for this method call. This is how we use an object of provider class.What happens internally:
once we created an object using new oiperator,the required arguments needs to be passed to the constructor.The JRE allocates sufficient memory to store fields of the object and initailizes its state.When initialization is done,the JRE returns a reference to the new object. So we can say the constructor returns an object reference to the object stored in memory.The default constructor takes no arguments and contains no code.It is provided automatically by the compiler if developer has not provided any constructor in the class.
But this is theoretical,how to execute the object?
Well we will execute the object of a provider class by inserting them a container class and use main method to trigger the execution.
Most Java applications may have any number of classes but they will surely have a single main that should trigger the execution.
An Example

public class MyContainerClass{
public static void main(String args[])
{
MyClass myObj=new MyClass();
myObj.setFirstName("Xavior");
}
}
 
In order to create an instance of class MyClass, We need to create an container class , then we can create the instance. The main is the starting function to kick of execution.


Guidelines for object creation:

  • An object by convention starts with a small letter like obj.
  • The object must be able to perform that method call.
Data member of an object
Each object keeps its own storage for its data members,the data members are not shared among objects.We may have any number of classes, but they will have no impact of our program until and unless we create an object from that class.

class Myclass{
int i;
float f;
boolean b;
}
//this class does not anything unless we create an object using new operator
Myclass mc=new Myclass();
 
We can assign values to the data members by the object name(handle) by a dot(.) operator
like-

mc.i=10;
mc.f=1.0f;
mc.b=false;
 
our object may also contain other objects which we would like to call a function like-
System.out.println("Hello Java");
It means that select out from class System and call println() method.
Scope of Objects
Java objects do not have the same lifetimes as primitives.When we create a java object using new,it hangs around past the end of the scope.

{
String myStr=new String("java");
}
//end of scope of myStr
 
The handle myStr vanishes at the end of the scope.However the string object myStr was pointing to,is still occupying memory.In the above code,there is no way to access the object because it is out of scope post this code line. Its turns out that because objects created with new operator stay around,as long as we want them.In Java it makes sure the objects are available when they are needed. Once objects created they fill up memory that halts the program.Java has a garbage collector ,which is a process running in the background(low priority execution and does not interfere program execution).The garbage collector looks at all the objects created by new and figures out which one's are not being referenced any further.Then it release the memory for those objects.This memory can be used by new objects.Thus a java coder never has to worry about reclaiming memory.This eliminates the problem of memory leakage where the programmer forgets to release memory.
Methods,arguments and return value:
Initially a function is termed as a named subroutine.Method is described as "a way to do something".Other way,methods in java determine the messages,an object can receive.the structure of the method is as follows:

returnType method Name(argumentList)
{
//method body
//return statement
}
 
returnType is the type of the value that pops out of the method after we call it. methodName is the meaningful name we can imagine and identifies the method. Argumentlist is the list of the type of argument and names for the information we want to pass to the method.If we try to call the wrong method for an object ,we will get a compile time error.The generic syntax for calling a method:
objectName(handle).(dot).methodName() with argument or without any argument.
If the class on whose handle we call the method (),has the method written,we will be able to perform the method call.
The return value must compatible with the return value defined in the method signature.
The call of the method is commonly referred as sending the message to the object.


All About Class and Object in Java All About Class and Object in Java Reviewed by Animesh Chatterjee on October 22, 2018 Rating: 5

No comments:

Powered by Blogger.