Scientech Easy Class and Objects in Java with Realtime examples | Scientech Easy

Saturday, April 6, 2019

Class and Objects in Java with Realtime examples

In this tutorial, we will learn the basic of Class and Objects in Java with realtime examples which is a very important topic for beginners to understand the concept of core java programming. You know that Java is an object-oriented programming language. In the object-oriented programming language, we can design a program using class and objects. So Let's start first to understand the concept of an object in Java.

Objects in Java

An object in Java is any real-world things that have properties and actions. In other words, an entity that has state and behavior is known as an object. Here, State represents the properties and Behaviour represents the actions or functionality.

An object has three characteristics:
1. State: State represents the properties of an object. It is represented by the instance variable/attribute of an object. The properties of an object are important because the outcome of functions depend on the properties.
2. Behavior: Behavior represents functionality or actions. It is represented by methods in Java.
3. Identity: Identity represents the unique name of an object. It differentiates one object from the other. The unique name of an object is used to identify the object.
Let's take a real-world example to understand all these points clearly.

Realtime Examples of Objects in Java

Realtime example 1:
We are taking the example "person". A person has three characteristics: Identity (name), State (properties), and behavior (actions or functionality). Consider the below image.
Class and objects in Java
In the above image, the First state/property of the person (object) is black hair which can be represented in Java like this: hairColor="black"
In the same way, the second property of the object is eye color which can be represented in Java like eyeColor="black" and so on. These are called attributes which define the properties of the person.

Let's consider the behavior or actions of a person. The actions or behavior of the person may be "eat, sleep, walk, play, and study". These actions is represented in Java like this: eat(), sleep(), walk(), play(), and study(). These are called methods
Key points:
Thus, when the properties and actions are combined together of any real-world object make an object in Java.

Note: Noun in English represents properties or state of an object and it can be represented with the help of variables whereas verbs represent action/behavior which can be represented with the help of methods.

Realtime example 2: Let's take one more interesting example 'Phone Samsung Galaxy'. If I tell you to represents this phone in Java in the form of an object then How will you do like that?
You can do that very easily. Ask two questions:

What it has? (Properties)   and What it does? (Actions)
Properties are width=6.2 or  "6.2 inch", height=13.6 or "13.6 cm", color="black", os="Android", price=1000 or "1000$", brand="Samsung", and weight="130 gm". All these are nouns called attributes. 
Actions/Behavior are call(), sendSms(), runApp(), browserInternet(), sharing(). Thus, a phone object is comprised of the properties that the phone has and actions that phone does.

Realtime example 3: Another example we can take "Pencil". A pencil is an object. Its name is Natraj. State: the color is black. Behavior: It is used to write so writing is behavior.
Thus, You can take any object around you and think about what property it has? and What action it does?

Class in Java

In Java programming, a class is basically user-defined data types which act as a template for creating objects of the identical type. It represents the common properties and actions (functions) of an object. In other words, a class can also be defined as "a class is a group of objects which are common to all objects of one type".
Key points:
A class is the type of an object. 
Let's understand with real-time examples.

Realtime Examples of Classes in Java

Realtime example 1:
Let us consider two objects Samsung Galaxy S4 and iPhone. Suppose Samsung Galaxy S4 have some properties like width="6.98 cms", height="13.6 cm", OS="Android", brand="Samsung", price="1000$" and Actions are call(), sendMessage(), browser(), share(). 
Now, suppose iPhone has some properties such as width="5.86 cm", height="12.3 cms", OS="iOS", brand="Apple", price="1200$" and actions are call(), sendMessage(), browse(), share(). 
Both objects have some different properties and actions but the type is the same "Phone". This is the class. i.e the name of the class is "Phone".

Realtime example 2:
Consider two objects one boy and one girl. The boy has some properties like hairColor="black", eyeColor="black", skinColor="Fair", height="5.10 inch", weight="65 kg" and actions are read(), play(), sleep(), walk(). 

Now, The girl has some properties like hairColor="Brown", eyeColor="brown", skinColor="milky white", height="5.4 inch", weight="50 kg" and actions are read(), play(), sleep(), walk(). but the type of both is the same. i,e Person. So the class name is 'Person'.

Declaration of Class in Java

A class can be declared using the keyword class followed by a class name. It has also a body within braces. A general syntax to declare a class is shown below.
     modifierName class className
          // class body.

In general, a class can have the following components to act as a template:
1. Modifiers: A class can be either public access or default access. But the member of classes can be public, private, default, and protected. All these are the access modifiers.

2. Class name: By convention, a class name should begin with a capital letter and subsequent characters lowercased (for example Student). If a name consists of multiple words, the first letter of each word should be uppercased( for example CollegerStudent). A class name can also start with an underscore ''_". The following class name can be valid such as _, _Student.
Key points:
Keywords cannot be a valid class name. For example, class, true, null, etc are not accepted as a class name.

3. Body: Every class's body is enclosed in a pair of left and right braces. In the body,  a class can contain the following members.
     class class_name {
    // Class body starts here.
             // Members of a class.
                    1. Field declarations;
                    2. Constructor declarations;
                    3. Method declarations;
                    4. Instance block declarations;
                    5. Static block declarations;
               } Ends here.
If you are writing a simple program, everything must reside inside the body of the class. Let's see in brief about all the members of the class.

Fields: Fields are data member variables of a class that stores data or value in it. It specifies the state or properties of the class and its object. It may be a Local variable, Instance variable or Static variable.

Constructor: A constructor is used to create an object. Every class must be at least one constructor otherwise, no object can be created of the class. If you don't explicitly define a constructor, the compiler automatically adds a default constructor inside the class. A constructor can be divided into two types such as Default constructor and User-defined constructor.

Method: A method defines action or behavior of the class that a class's object can perform. It has a body within braces. In the body, we write the code that performs the actions. It may be an Instance method or a Static method.
Block: A block is mostly used to change the default values of variables. It may be an instance block or static block.
Interface: It is used to achieve multiple inheritances in Java. 

Method main: A class has also a main method that provides the entry point to start the execution of any program. The signature of the main method is as follows.
   public static void main(String[] args) {
The JVM executes everything between the curly braces { } of the main method. Every java program has at least one class and at least one main method.

Flow of Execution of Program in Java

1. Out of five elements declared inside the class body, the static variable, static block, and static method are executed first during the loading of the dot class file.
2. The instance variable is executed during the object creation.
3. When the object is created, first, an instance block is executed before the execution of a constructor.
4. After the execution of an instance block, the constructor part will be executed.
5. After the execution of the constructor part, the instance method is executed.
6. The local variable is executed inside the method, constructor or block.

A simple class example
Suppose, Student is a class name and the name, rollNo, id, age of the students will be its properties. The "public" is the access modifiers. Let's see these in Java syntax.

    public class Student { // Declaration of state/Properties. String name; // Instance variable. int rollNo; // Instance variable. int id; static int age; // Static variable. // Declaration of constructor. Student() { // Constructor body. } // Declaration of Actions. void display() // Instance method. { // method body. } // Declaration of instance block. { // block body. } ....... ....... public static void main(String[] args){ ....... } }
Key points: 
1. You can create any number of objects of a class.
2. The process of creating an object of a particular class is called instantiating of an object.
3. The object is called an instance of the class.

Difference between Class and Object in Java

1. A class is a user-defined data type whereas an object is an instance of the class data type.
2. A class generates objects whereas an object gives life to a class.
3. Classes do not occupy memory location but objects occupy memory location.
4. Classes cannot be manipulated due to not available in the memory location but objects can be manipulated.

Final words 
Hope that this article has covered all the basic topics related to classes and objects in Java with real-time examples and program. We hope that you have enjoyed this article.
Thanks for reading!
Next ➤ How to create an object in Java
Next ⏩