Java / Guided lesson
Understand Java Classes and Objects
Build a strong foundation in Java programming. Explore classes, objects, methods, constructors, inheritance, and object-oriented programming with practical coding examples.
Browse all Java topicsWorked example
Java is a class-based, object-oriented programming language. A class defines the structure and behavior of objects. Objects are instances of classes. Constructors initialize objects, while methods define their behavior.
class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Marks: " + marks);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("Rahul", 90);
student.displayDetails();
}
}Expected output
Name: Rahul
Marks: 90Check your understanding
What is the difference between a class and an object in Java?
Show answer
A class is a blueprint that defines fields and methods. An object is an instance of that class created in memory. Multiple objects can be created from the same class, each with its own instance data.
Try it yourself
Add a method called checkResult() that prints Pass when marks are greater than or equal to 40, otherwise prints Fail.
Show solution
void checkResult() {
if (marks >= 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
// Add this method inside the Student class.
// Call student.checkResult() inside main.
// Output: Pass