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:
Classes provide a convenient method for packing together a group of logically related data items and functions that work with them.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.

A class is an user defined data types with a template that provides the definition of the properties.Once the class type has been defined , we can create variables of that type using declaration that are similar to the basic type declarations that are similar to the basic type declaration. These variables are called instance of the class.(They are objects of that class)

The basic structure of the class is :

class className[extends superclass][implements someOtherclass]
[field declaration]
[methods declaration]
Filed declaration
Data encapsulated in a class by placing data fields inside the body of the class definition. These variables are called instance variables as they are created whenever an object of the class is instantiated. The declaration is exactly same as local variables.

class Rectangle{
int length;
int width;
Once they are declared , there is no space allocated to them.
Design of a class
While designing qualifier "-" signifies private and "+" signifies public.
-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)
+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]

Method declaration:
A class with only data fields has no life as there is no methods that operate on that data.The objects created by such class can not respond to any message.So it is necessary to design methods. Methods are declared inside the body of the class but immediately after the declaration of the instance variables.

[access modifier][specifier][return type]methodname(parameterList)
//method body
The four basic parts of the valid method are as follows:

  1. The name of the method(methodname)
  2. The return type of the method
  3. the list of parameters
  4. the body of the method.

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

public class MyClass{
private String firstName();
public void setFirstName(String 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

The return type could be inbuilt data types or a class object.A method may not have any valid return value,in such case the return type will be void.The argument list is enclosed with parentheses.The list contains variables in a list separated by comma.A method may also take no input in such case the argument list is empty parentheses."()" .

Most of the times,when we use classes,we will have many methods and variables within the class.Instance variables and methods in classes are accessible by all methods in the class but a method can not access variables declared in other method.

class abc{
int x;
void method1()
int y=x;

void method2()
int z;
//illegal as y is part of method1


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 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.

Object o=new Object() //is legal but not sure where to use its methods
An Object:
Instance of a class is called object .An object in java essentially means a block of memory that contains space to store all the instance variables.Thus ,Object and instance are interchangeable in java.So creating an object is referred to as instantiation of an object. 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.Calling a specific method in an object is referred as sending a message.Objects can be created using the new operator.The new operator creates an object of the specified class and return the reference of that object.
Construction of an Object

MyClass mc=new MyClass();
MyClass mc;//declare the object
mc=new MyClass();//instantiate the object
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.We can create n numbers of objects by using this syntax:

MyClass mc1=new MyClass();
MyClass mc2=new MyClass();
MyClass mc3=new MyClass();
MyClass mcn=new MyClass();
Each object holds some amount of memory space and has its own copy of instance variables of its class.It also signify that any change to the variable of its one object have no effect on the variables of another.
We can create two or more references to the same object.

MyClass mc1=new MyClass();
MyClass mc2;
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.

String name=mc.getFirstName();
All variables of an object must be assigned some value before they are used.From outside of the class we can not assign/access the variables directly as most of the cases they are private.To do this we need to account object and a dot (.) operator.

if the instance variables are public then we can follow this approach:

class MyClass{
public int x;
public int y;

class Test{
MyClass mc1=new MyClass();
if the instance variables are private then we can follow this approach:

class MyClass{
private int x;
private int y;
//we can define an argumented constructor
public MyClass(int x,int y)
//or we can define some  getter or setter method
public void setValues(int x,int y)
class Test{
MyClass mc1=new MyClass(10,15);
MyClass mc1=new MyClass();
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();
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

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.