Java Class and Object Relationship
Class and Object in Java
In Java, a class is a blueprint or prototype that defines the variables and methods common
to all objects of a certain kind. An object is an instance of a class. When a class is defined, no
memory is allocated until an object of that class is created.
Member Variables and Member Methods
Member Variables:
These are variables that are declared inside a class but outside any method, constructor, or
block. They are also called instance variables as they are created when an object is
instantiated.
Member Methods:
These are functions defined inside a class that operate on the instance variables. They
define the behaviors of the objects of the class.
Example:
public class Car {
// Member Variables
String color;
int speed;
// Member Method
void drive() {
System.out.println("The car is driving.");
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of Car
Car myCar = new Car();
myCar.color = "Red";
myCar.speed = 100;
myCar.drive();
}
}