scripti

Class & object

Class is Blueprint of object, just like a house blueprint, it does not cost anything but only paper.

Object is the real implementation of that blueprint and cost resources such as memory.

Student Class

  class Student {

    Student() {}

    String id;
    String name;
    String email;
  }

the id, name, email are properties of Student class.

constructor

The constructor is a special method which will be available in all classes.

Student Object

In java to instantiate a class we will use new operator and by using it we call the constructor

instantiation is nothing but allocating memory to accomdate the properties and their methods. Memory for objects are allocated in heap memory (we will talk more about memory in upcoming chapters)

To allocate memory to the object ( Instantiate the object), below is the statement

Student studentObj = new Student(); 

Diagram showing the process of Java object creation, including memory allocation and initialization.

What do you think the vlaue of studentObj variable?

The Student class is instantiated, thus the memory is being allocated for the attributes declared in the class

studentObj is having reference to the object in the heap memory not the object itself.

Lets declare more classes

Student class


  class Student {

    Student(String id, String name, List<Course> courses){
      this.id = id;
      this.name = name;
      this.courses = courses;
    }

    String id;
    String name;
    List<Course> courses;

  }

Course Class

  class Course {
    
      Course(String id, String name, Professor professor) {
      this.id = id;
      this.name = name;
      this.professor = professor;
    }

    String id;
    String name;
    Professor professor;
  }

Professor Class

  class Professor {

    Professor(String id, String name) {

      this.id = id;
      this.name = name;
    }

    String id;
    String name;

  }

Creatign objects


  class Test {

      public static void main(String[] arg) {
          Professor professor = new Professor("1", "Jhon");

          Course c1 = new Course("1", "DSA", professor);
          Course c2 = new Course("2", "Java Programming", professor);

          List<Course> courses = List.of(c1, c2);

          Student studentObj = new Student("1", "Mathew", courses);

      }
  }

The above code will create the objects as shown in the below diagram.

Shallow Copy

Diagram showing Object reference Java

from this diagram, you can see, the object creation ( allocation of memory) happens only during the new keyword usage everytime when ever the assingment happens through the refernece its always the refernce to the object ( we can call it as remote)

So by having the object reference as value, we will be giving direct access to the object itself, its vital to understand this concept to avoid the basic mistake during the call by value and call by refernce, shallow copy and deep copy issues during object creation and copy.