Java Classes and Objects Theory and Practical Example

In this tutorial post we will take an In-Dept understanding of Java Classes and Objects by understanding the theoretical and practical aspect. We will see program example at the end too.

What is a Class  ?

  • It is a template or blueprint from which objects are created.
  • It is a logical entity. It can’t be physical.
  • A class in Java can contain:
    • Fields (variables)
    • methods
    • constructors
    • blocks
    • nested class and interface
What is n Object ?
  • An entity that has state and behavior is known as an object.

An object has three characteristics:

  1. state: represents data (value) of an object.
  2. behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
  3. identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely.
Relation Between Class and Object –
  • Object is an instance of a class.
  • Class is a template or blueprint from which objects are created.
  • So object is the instance(result) of a class.
  • In another way, we can say that objects are variables of type class

Java Classes and Objects relation

In this example you can see that the class is related or considered as the blueprint of the building, however the objects are the actual physical buildings. 

Some Important Concepts that come along with Classes and Objects are –

  • Instance variables
  • Methods
  • new keyword
Instance variable in Java
  • A variable which is created inside the class but outside the method, is known as instance variable. Instance variable doesn’t get memory at compile time. It gets memory at run time when object(instance) is created. That is why, it is known as instance variable.
Method in Java
  • In java, a method is like function i.e. used to expose behavior of an object.
Advantage of Method
  • Code Reusability
  • Code Optimization
new keyword in Java
  • The new keyword is used to allocate memory at run time. All objects get memory in Heap memory area.
Program Example –
package mystudentexample;

class Student{
    int id;  // instance variables
    String name; // instance variables
}

public class MyStudentExample {
  
    public static void main(String[] args) {
     
        Student object1 = new Student();
        
        Student obj2;
        obj2 = new Student();
        
        obj2.id = 2;
        obj2.name = "Simple Snippets";
        
        object1.id = 1;
        object1.name = "Tanmay";
        
        System.out.println(object1.id);
        System.out.println(object1.name);
        System.out.println(obj2.id);
        System.out.println(obj2.name);
        
    }
    
}
Output
1
Tanmay
2
Simple Snippets
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *