Java Classes and objects

18-Sep-2024

Learn how to define and use classes and objects in Java for building real-world applications


Classes


A class is a blueprint for creating objects. Class combines data and method and work as a single unit. Class can contain fields ( variables ) and methods.



Fields are the attributes or properties of class.

Methods are describe the behavior.


Components of class:


1. Fields: These are the variables defined inside the class


2. Methods: These are independent code blocks that can complete a specific task.


3. Constructor: Constructor is a special method. Class and constructor names are the same


4. Modifiers: Modifiers are private, public, protected, etc. These are defines how can be access the class properties and methods.


A simple class syntax:



class MyClass{

}



Now a class syntax with the four class components:



class Person{
public String person_name; // class fields (attributes or properties) with public modifier
private String person_address; // class fields (attributes or properties) with private modifier


// Constructor take the fields value by constructor parameters and set the value to class fields
public Person(String person_name, String person_address) {
this.person_name = person_name;
this.person_address = person_address;
}

// Class method
public void printPersonDetails(){
System.out.println("Person name is : " + person_name + " and address is : " + person_address);
}
}



Objects


Object is an instance of a class. It is a real world entity. Syntax of create a object is:



// Class_name object_name = new Class_name();



With the Person class example, we can create objects for a different person. Here the important thing is the Person class constructor takes 2 parameters. That's why we need to provide these values when Constructor is calling.


Now let's create a class Main which will have a main method and here let's create multiple objects of the Person class



class Main{

public static void main(String[] args) {

// a object of john
Person john = new Person("John", "New York");
// now we can access the class method and fields by john
john.printPersonDetails(); // output : Person name is : John and address is : New York



// another object of rahim
Person rahim = new Person("Rahim", "Dhaka");
// now we can access the class method and fields by rahim
rahim.printPersonDetails(); // output : Person name is : Rahim and address is : Dhaka

}
}



We can create multiple objects of a class and each object is different from other objects



Comments