Java Classes and Objects

🔹 Java Classes and Objects

Java is an object-oriented programming language, so classes and objects are the foundation of Java programs.


✅ 1. What is a Class?

A class is a blueprint or template that defines the attributes (variables) and behaviors (methods) of objects.

class Car { // Class
String brand; // Attribute (variable)
int year;

void displayInfo() { // Behavior (method)
System.out.println("Brand: " + brand + ", Year: " + year);
}
}

  • Class name starts with an uppercase letter by convention.

  • Attributes → Store object data.

  • Methods → Define actions the object can perform.


✅ 2. What is an Object?

An object is an instance of a class. It has its own copy of the class attributes and can use class methods.

public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // Creating object car1
car1.brand = "Toyota"; // Setting attributes
car1.year = 2022;
car1.displayInfo(); // Calling method

Car car2 = new Car();
car2.brand = "Honda";
car2.year = 2023;
car2.displayInfo();
}
}

📌 Output:

Brand: Toyota, Year: 2022
Brand: Honda, Year: 2023

✅ 3. Object Syntax

ClassName objectName = new ClassName();
  • new keyword creates a new object in memory.

  • Each object has its own copy of instance variables.


✅ 4. Multiple Objects Example

class Student {
String name;
int age;

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

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

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

s1.display();
s2.display();
}
}

📌 Output:

Name: Alice, Age: 20
Name: Bob, Age: 22

✅ 5. Key Points

  • Class → Blueprint (defines properties and behaviors).

  • Object → Instance of a class (has its own state).

  • Attributes → Variables inside a class.

  • Methods → Functions inside a class.

  • new keyword → Creates object in memory.

  • Objects can have different values for the same attributes.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

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