Java: Class, Object, and Method
1. Class in Java
A class is a blueprint or template for creating objects. It defines attributes (fields) and behaviors (methods).
Syntax:
class ClassName {
// Fields
int x;
// Methods
void sayHello() {
System.out.println("Hello!");
2. Object in Java
An object is an instance of a class. You create an object using the `new` keyword.
Syntax:
ClassName obj = new ClassName();
3. Method in Java
A method is a block of code that performs a specific task. It belongs to a class and can be called on an
object.
Java: Class, Object, and Method
Syntax:
returnType methodName(parameters) {
// code
Example:
class Car {
String color;
int speed;
void drive() {
System.out.println("The car is driving at " + speed + " km/h.");
void setDetails(String c, int s) {
color = c;
speed = s;
void showInfo() {
System.out.println("Color: " + color);
System.out.println("Speed: " + speed);
}
Java: Class, Object, and Method
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.setDetails("Red", 100);
myCar.showInfo();
myCar.drive();
Output:
Color: Red
Speed: 100
The car is driving at 100 km/h.
Summary
Class: Blueprint that defines objects
Object: Instance of a class
Method: Function defined inside a class