Java Classes and Objects

🧠 What is a Class?

A class in Java is a blueprint or template used to create objects. It defines properties (variables) and behaviors (methods) that the object will have.

Think of a class like a car designβ€”it defines how cars are made, but it’s not a real car itself. The actual cars built from that design are the objects.

βœ… Syntax of a Class:

class ClassName {
// fields (variables)
// methods
}

🧠 What is an Object?

An object is an instance of a class. It holds real values for the fields defined in the class and can use the class methods.

You create (instantiate) objects using the new keyword.

ClassName obj = new ClassName();

πŸ§ͺ Example:

class Student {
String name;
int age;

void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Amit";
s1.age = 20;
s1.displayInfo();
}
}

πŸ” Output:

Name: Amit
Age: 20

πŸ”Έ Fields, Methods, and Access:

  • Fields: Variables inside a class.

  • Methods: Functions that define behavior.

  • Access: Use the dot operator (.) to access fields and methods from an object.


🧾 Important Points:

  • A class is not memory-consuming until objects are created.

  • Objects have state (field values) and behavior (methods).

  • You can create multiple objects from the same class.


πŸ” Multiple Objects Example:

Student s2 = new Student();
s2.name = "Ravi";
s2.age = 22;
s2.displayInfo();

Related Posts