DEV Community

Arun Kumar
Arun Kumar

Posted on

πŸ‘¨β€πŸ’» Understanding Java Classes and Objects with a Human Example

In Java, classes and objects are the foundation of Object-Oriented Programming (OOP).

πŸ”Ή What is the Human Class?
A class in Java is like a blueprint.
In our case, the blueprint is a Human. Every human has:

πŸ“ Name

πŸŽ‚ Age

⚧ Gender

πŸŽ“ Qualification

Here’s the class definition:

class Human {
String name;
int age;
char gender;
String qualification;

public void getInformation() {
    System.out.println(name + " " + age + " " + gender + " " + qualification);
}
Enter fullscreen mode Exit fullscreen mode

}
πŸ”Ή Creating Objects from the Human Class
Once we have the Human class blueprint, we can create actual objects (humans).

Example:

public static void main(String ar[]) {
Human bharath = new Human();
bharath.name = "Bharath K";
bharath.age = 25;
bharath.gender = 'M';
bharath.qualification = "MSc Maths";

bharath.getInformation(); // Output: Bharath K 25 M MSc Maths
Enter fullscreen mode Exit fullscreen mode

}
πŸ‘‰ Here, bharath is an object of the Human class.
We set values for his properties and then call the method getInformation() to display them.

πŸ”Ή Creating Multiple Objects
We can also create another object from the same class:

Human mani = new Human();
mani.getInformation(); // No values assigned, so it prints: null 0 οΏ½ null
⚠️ Since we didn’t assign values to Mani’s details, Java uses default values:

String β†’ null

int β†’ 0

char β†’ blank (οΏ½)

πŸ”Ή Key Takeaways
Class = Blueprint (Human)

Object = Real Instance (Bharath, Mani)

Fields/Properties store data (name, age, gender, qualification)

Methods define behavior (getInformation())

If values are not set, Java assigns default values

Top comments (0)