1.4 Class and Object
How Java models real-world things using blueprints (classes) and concrete instances (objects), and how encapsulation keeps data safe.
What are Classes and Objects?
Java is a fully object-oriented language. Almost everything you work with is either a class (a definition) or an object (a usable thing created from that definition).
- Class: a blueprint or template that describes what data (fields) and behavior (methods) its objects will have.
- Object: a specific instance of a class that lives in memory and can store its own values.
- Real-world view:
Studentis a class, while each enrolled student (Ram, Sita, etc.) is an object.
Example 1: Simple Class and Object
To create an object, you write the class name followed by a variable name and use the new keyword. Members are accessed using the dot (.) operator.
Student.java (Class & Object)
class Student {
String name;
int roll;
String faculty;
}
class StudentDemo {
public static void main(String[] args) {
Student ob = new Student(); // Creating object
ob.name = "Nishanta";
ob.roll = 10;
ob.faculty = "BE Computer";
System.out.println("Name = " + ob.name);
}
}class Student: defines a new class with three fields (name,roll,faculty).Student ob = new Student();: creates a new object and stores its reference inob.ob.name = "Nishanta";: assigns values to the object's fields using the dot operator.System.out.println("Name = " + ob.name);: reads data back from the object and prints it.
Example 2: Data Hiding and Member Access
Directly exposing fields can be risky. Encapsulation means keeping fields private and providing public methods to change or read them.
Student1.java (Encapsulation)
class Student1 {
private String name; // Restricted access
private int roll;
public void setInfo() {
name = "Nishanta";
roll = 11;
}
public void showInfo() {
System.out.println("Name: " + name);
System.out.println("Roll: " + roll);
}
}
class StudentDemo1 {
public static void main(String[] args) {
Student1 ob = new Student1();
ob.setInfo();
ob.showInfo();
}
}- Fields
nameandrollare declared asprivate, so they cannot be accessed directly from outside the class. setInfo()initializes the fields; it acts like a controlled writer.showInfo()prints the values; it acts like a safe reader.- The main method only works with public methods of
Student1, not with its internal data directly.
Sample Output
When you run the above programs, the console will display something like this:
Name = Nishanta
Name: Nishanta
Roll: 11