Module 2 ยท Objects and collections Lesson 4 of 15
Classes, objects and constructors
A class is the design and an object is the thing built from it. A constructor is the method that runs when you build one, and it is where you make an object impossible to create in a broken state.
The concept
A class is the blueprint and an object is the thing built from it: class Student { String name; int marks; } then Student s = new Student(). Fields hold the state, methods hold the behaviour, and a constructor sets the object up so it is never half-built.
The four ideas to be able to define out loud: encapsulation (fields private, access through methods), inheritance (extends, for an is-a relationship), polymorphism (one method name, several implementations) and abstraction (an interface describing what, not how). Service companies test these in the first ten minutes, and a fresher who can give an example from their own project stands out.
public class Student {
private final String name;
private int marks;
public Student(String name, int marks) { // constructor
this.name = name;
this.marks = marks;
}
public String getName() { return name; }
public void addMarks(int extra) { this.marks += extra; }
}
Student s = new Student("Asha", 72);
s.addMarks(6);Common mistakes
The mistake is public fields edited from everywhere, which is what makes a small project impossible to change later. Make fields private, add getters and setters where they are actually needed, and pass values through the constructor instead of setting five fields after new.
Worked example
class Student with a constructor Student(String name, int marks) rejects an empty name at the door. A setter that validates later is a weaker design, and interviewers ask which you would pick and why.
Your practice task
Model a Student and a Course: two classes, constructors, private fields, getters, and a method that prints one line per student.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
A class is the blueprint and an object is the thing built from it: class Student { String name; int marks; } then Student s = new Student().
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task โ do them and the final project brief writes itself.