Creating a Class and Objects

Your First Class

Example

Create objects with the new keyword. Use the dot . to access fields.

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Kavya";
        s1.rollNo = 101;
        s1.cgpa = 8.7;

        Student s2 = new Student();
        s2.name = "Rohit";
        s2.rollNo = 102;

        System.out.println(s1.name + " " + s1.rollNo + " " + s1.cgpa);
        System.out.println(s2.name + " " + s2.rollNo + " " + s2.cgpa);   // cgpa not set -> 0.0
    }
}

class Student {
    String name;
    int rollNo;
    double cgpa;
}

Output

Kavya 101 8.7
Rohit 102 0.0

Key Points

  • Each object has its own copy of the fields. Changing s1.name does not change s2.name.
  • Fields get default values: 0, 0.0, false, null.
  • A variable like s1 holds a reference to the object, not the object itself.
  • In real projects each public class lives in its own file (Student.java). In these examples extra classes sit in the same file without public.