Java Objects
What is an Object?
- An object is a real-world entity created from a class.
- It has:
- State (fields/variables)
- Behavior (methods/functions)
An object is an instance of a class.
How to create an Object?
ClassName objectName = new ClassName();
Example:
class Car {
String brand;
int year;
void displayInfo() {
System.out.println(brand + " - " + year);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Object created
myCar.brand = "Tesla";
myCar.year = 2022;
myCar.displayInfo(); // Method called using object
}
}
Output:
Tesla - 2022
Real Life Example
Real World | Java |
---|---|
"Dog" (concept) | class Dog {} |
"Tommy", "Bruno" (actual dogs) | Dog tommy = new Dog(); Dog bruno = new Dog(); |
Important Points about Objects
- Object creation happens using the new keyword.
- Object stores data separately (each object can have different values).
- Dot (.) operator is used to access fields and methods.
Example:
myCar.brand = "BMW"; // Accessing field
myCar.displayInfo(); // Calling method