Classes And Objects
A class defines a new type by grouping data with the operations that use it. An object is one instance created from that definition.
Putting a student's data and behavior together keeps related code in one place. Different Student objects can have different names and marks while sharing the same method definitions.
Create one object
class Student {
String name;
int marks;
void display() {
System.out.println(name + ": " + marks);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.name = "Maya";
student.marks = 85;
student.display();
}
}
Output:
Maya: 85
new Student() creates an object. The reference stored in student is used to set its fields and call the display method.
Fields receive default values, but relying on half-initialized objects leads to bugs. Constructors provide a safer starting point.
Create a Book object, set its title and price, then display it.