1. Introduction to Classes and Objects
1.1 Overview
Classes and objects are used to structure programs in Java.
1.2 Relationship
- Class → Blueprint
- Object → Instance of a class
1.3 Real-World Example
- Class → Car
- Object → BMW, Audi
1.4 Importance
- Helps organize code
- Makes programs modular and reusable
2. What is a Class
2.1 Definition
A class is a blueprint used to create objects.
2.2 Structure
A class contains:
- Variables (fields)
- Methods (functions)
2.3 Example
class Student {
String name;
int age; void display() {
System.out.println(name + " " + age);
}
}
2.4 Naming Convention
- Use PascalCase
- Example:
StudentRecord
3. What is an Object
3.1 Definition
An object is an instance of a class.
3.2 Characteristics
- State → variables
- Behavior → methods
- Identity → unique instance
3.3 Memory Allocation
Objects are created in heap memory.
3.4 Example
Student s1 = new Student();
4. Creating Classes and Objects
4.1 Creating Object
Student s1 = new Student();
4.2 Accessing Members
s1.name = "Pooja";
s1.age = 20;
4.3 Calling Method
s1.display();
4.4 Multiple Objects
Student s2 = new Student();
4.5 Complete Example
class Student {
String name;
int age; void display() {
System.out.println(name + " " + age);
} public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Pooja";
s1.age = 20;
s1.display();
}
}
5. Constructors
5.1 Definition
A constructor is a special method used to initialize objects.
5.2 Characteristics
- Same name as class
- No return type
- Automatically called
5.3 Default Constructor
class Student {
Student() {
System.out.println("Constructor called");
}
}
5.4 Parameterized Constructor
class Student {
String name; Student(String n) {
name = n;
}
}
5.5 Constructor Overloading
Student() {}
Student(String name) {}
5.6 this Keyword
this.name = name;
5.7 Constructor vs Method
| Constructor | Method |
|---|---|
| Initializes object | Performs action |
| No return type | Has return type |
6. Instance vs Static Members
6.1 Instance Members
- Belong to object
- Each object has its own copy
class Student {
String name;
}
6.2 Static Members
- Shared among all objects
- Belong to class
class Student {
static String college = "ABC";
}
6.3 Accessing Static Members
Student.college;
6.4 Differences
| Instance | Static |
|---|---|
| Object-based | Class-based |
| Separate copy | Shared copy |
6.5 When to Use Static
- Common values
- Utility methods
Conclusion
Classes and objects are the core of Java programming. By understanding how to create and use them, along with constructors and static members, beginners can build structured and reusable applications. These concepts are the foundation for advanced topics in Java and real-world software development.
Leave a Reply