Java Classes and Objects
Java Classes/Objects
A class in Java is a blueprint used to create objects. It is a part of Object-Oriented Programming (OOP), where everything is based on classes and objects. A class contains variables (attributes) and methods (functions/actions).
An object in Java is a real-world instance of a class. It is created using a class and represents a specific entity that has state (data/attributes) and behavior (methods/actions).
An object in Java is a real entity created from a class that has properties (data) and methods (actions).
In Java, you can create multiple classes in a single program file. Each class can have its own variables (data) and methods (functions). One class is usually used as the main class where the program starts running, and other classes are used to support it.
Β
Example
class Car {
Β Β // Attributes (data)
Β Β String color;
Β Β int speed;
Β Β // Method (behavior)
Β Β void drive() {
Β Β Β Β System.out.println("Car is driving");
Β Β }
}
public class Main {
Β Β public static void main(String[] args) {
Β Β Β Β // Creating object of Car class
Β Β Β Β Car myCar = new Car();
Β Β Β Β // Assigning values to object
Β Β Β Β myCar.color = "Red";
Β Β Β Β myCar.speed = 120;
Β Β Β Β // Calling method using object
Β Β Β Β myCar.drive();
Β Β Β Β // Display values
Β Β Β Β System.out.println(myCar.color);
Β Β Β Β System.out.println(myCar.speed);
Β Β }
}