Title here
Summary here
In Java, a class is a user-defined data type that acts as a blueprint for creating objects. It defines:
It encapsulates data for the object and methods to operate on that data.
An object is a runtime instance of a class. It represents an actual entity in the real world with:
Weβll model a real-world entity: Car
Car.java
β Blueprint (Class)public class Car {
// Fields (attributes)
String color;
int speed;
// Method (behavior)
void drive() {
System.out.println("The " + color + " car is driving at " + speed + " km/h.");
}
}
Main.java
β Creating and Using Objectspublic class Main {
public static void main(String[] args) {
// Creating first object
Car car1 = new Car();
car1.color = "Red";
car1.speed = 60;
car1.drive(); // Output: The Red car is driving at 60 km/h.
// Creating second object
Car car2 = new Car();
car2.color = "Blue";
car2.speed = 90;
car2.drive(); // Output: The Blue car is driving at 90 km/h.
}
}
Concept | Description |
---|---|
Car car1 = new Car(); | Instantiates a new object using the Car class |
car1.color = "Red"; | Sets the state of the object |
car1.drive(); | Invokes behavior defined in the class |
This approach adheres to Object-Oriented Programming (OOP) principles such as encapsulation and modularity.
Create a Student
class with:
name
(String)age
(int)introduce()
that prints:"Hi, my name is Alex and I am 21 years old."
In your main
method:
introduce()
method on bothβ Let me know if youβd like to proceed to: