What is a Class in Java?
A class in Java is a blueprint or template used to create objects. It defines the properties (fields) and behaviors (methods) of an object.
Basic Syntax of a Class
class ClassName {
// fields (variables)
// methods
}
Example 1: Basic Class with Object Creation
// Define a class
class Car {
// fields
String brand = "Toyota";
int speed = 120;
// method
void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
}
}
// Main class
public class Main {
public static void main(String[] args) {
// create an object of Car
Car myCar = new Car();
myCar.displayInfo(); // call method
}
}
Output:
Brand: Toyota
Speed: 120 km/h
Example 2: Class with Constructor and Parameters
class Student {
String name;
int age;
// constructor
Student(String n, int a) {
name = n;
age = a;
}
void showDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice", 20);
s1.showDetails();
}
}
Output:
Name: Alice
Age: 20
Components of a Class
Component | Description |
---|---|
Fields | Variables that store object data |
Methods | Functions that define behavior |
Constructors | Special methods to initialize objects |
Objects | Instance of a class |
Example 3: Multiple Objects from One Class
class Dog {
String breed;
void bark() {
System.out.println(breed + " is barking!");
}
}
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.breed = "Labrador";
d1.bark();
Dog d2 = new Dog();
d2.breed = "Pug";
d2.bark();
}
}
Output:
Labrador is barking!
Pug is barking!
Why Use Classes?
- To organize code using Object-Oriented Programming (OOP)
- To model real-world things (like Car, Student, Dog)
- For reusability and modularity
Keywords Related to Classes
class
– to define a classnew
– to create an objectthis
– refers to the current objectstatic
– to define class-level fields or methods
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.