Class
Class
A school program needs reliable data and clear rules. A class defines the fields and methods available on its instances. Separate student objects can use the same definition while storing different names.
Understand
A class defines the fields and methods available on its instances.
Apply
Trace the Java example, predict its output and explain the result before running it.
Avoid mistakes
A class definition does not create a student automatically. new constructs a particular object.
What is a Class?
A class in Java is like a blueprint for making cars. It defines what features the car will have (like color, engine type, or number of doors) and what actions it can perform (like start, stop, or accelerate). But the class itself isn’t the actual car — it’s just the design. Just like a car blueprint isn’t a car you can drive, a class isn’t an object — it simply describes how the object should be built and behave.
How to Declare a Class in Java
Declaring a class is simple. Here's the syntax:
class ClassName {
// Fields (variables)
// Methods (functions)
}
classis the keyword used to declare a class.ClassNameis the name you give to your class. By convention, class names start with a capital letter.- The class body is enclosed in curly braces
{ }. - Inside the class, you can define:
- Fields: variables that hold data for each object.
- Methods: functions that define what the object can do.
Flow diagram: key actions and decisions
These labels identify the actions and decisions in the original diagram; the list does not represent branch order. Follow the Java code for the exact execution path.
Explanation of the Class Diagram
class ClassName: This line declares a class namedClassName. It’s similar to the Java syntaxclass ClassName { ... }.-type field1and-type field2: These represent fields (also called attributes or variables) in the class.- The
-symbol means the fields are private, meaning they can only be accessed within the class. typeis a placeholder for the data type (likeint,String, etc.).
- The
+method1()and+method2(): These represent methods (also called functions) in the class.- The
+symbol means the methods are public, meaning they can be accessed from outside the class. - The empty parentheses
()indicate that the methods do not take any parameters in this diagram.
- The
Class diagrams help you visualize the structure of your class, including its data (fields) and behavior (methods), before writing the actual code.
Defining a Class
Let’s define a class called Car with a few attributes and a method to display its details.
Flow diagram: key actions and decisions
These labels identify the actions and decisions in the original diagram; the list does not represent branch order. Follow the Java code for the exact execution path.
class Car {
String brand;
int year;
void displayDetails() {
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}
Creating Objects from a Class
Once we have a class, we can create objects (instances) from it using the new keyword.
class Car {
String brand;
int year;
void displayDetails() {
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.year = 2020;
myCar.displayDetails();
}
}
Brand: Toyota
Year: 2020
Class Diagram
Flow diagram: key actions and decisions
- String[
These labels identify the actions and decisions in the original diagram; the list does not represent branch order. Follow the Java code for the exact execution path.
Explanation
- Car is a class with two private fields:
brandandyear. - It also has one public method:
displayDetails(), which prints the values ofbrandandyear. - Main is the entry point of the program. It contains the
main()method. - Inside
main(), an objectmyCarof classCaris created and initialized. - The line
Main --> Car : usesindicates that theMainclass uses theCarclass by creating and interacting with its object.
Here, we created an object myCar of type Car. We then assigned values to its brand and year fields. Calling displayDetails() printed those values to the console.
Example 3: Adding Constructors
A constructor is a special method used to initialize objects. Let’s modify our Car class to include one.
class Car {
String brand;
int year;
// Constructor
Car(String b, int y) {
brand = b;
year = y;
}
void displayDetails() {
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Honda", 2018);
car1.displayDetails();
}
}
Brand: Honda
Year: 2018
Key Concepts Around Classes
- Fields: Variables declared inside a class that define the state of an object.
- Methods: Functions defined in a class that describe its behavior.
- Constructors: Special methods to initialize objects. If not defined, Java provides a default one.
- Access Modifiers: Such as
public,private, andprotectedto control visibility.
Example 4: Using Multiple Objects
You can create multiple objects from the same class, each with its own set of data.
class Car {
String brand;
int year;
// Constructor
Car(String b, int y) {
brand = b;
year = y;
}
void displayDetails() {
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Ford", 2021);
Car car2 = new Car("Tesla", 2022);
car1.displayDetails();
System.out.println("---");
car2.displayDetails();
}
}
Brand: Ford
Year: 2021Brand: Tesla
Year: 2022
Importance of Classes
Classes bring structure to your code. Instead of writing repetitive logic, you define it once in a class and reuse it by creating objects. They support abstraction, encapsulation, inheritance, and polymorphism — all pillars of OOP and we shall learn each of them in detail in our next classes.
Remember
- Class name should start with an uppercase letter by convention.
- You can create as many objects from a class as you need.
- Fields store data; methods manipulate or display it.
- Constructor names must match the class name.
Important boundaries and mistakes
A class definition does not create a student automatically. new constructs a particular object.
Try the school example
Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: A class definition does not create a student automatically.
Java 17 · Main.java · complete practice program
public class Main {
interface Named {
String label();
}
static class Student implements Named {
static String school = "River School";
String name;
Student(String name) {
this.name = name;
}
public String label() {
return name;
}
}
public static void main(String[] args) {
Student a = new Student("Diya");
Student b = new Student("Aarav");
System.out.println(a.name + " / " + b.name);
}
}
Now change one thing: Rename only one object. Predict the new behavior before checking the worked variation.
Worked answer and reasoning
Java 17 · Main.java · source repeated for this answer
public class Main {
interface Named {
String label();
}
static class Student implements Named {
static String school = "River School";
String name;
Student(String name) {
this.name = name;
}
public String label() {
return name;
}
}
public static void main(String[] args) {
Student a = new Student("Diya");
Student b = new Student("Aarav");
System.out.println(a.name + " / " + b.name);
}
}
Expected output
Diya / AaravA class defines the fields and methods available on its instances. Separate student objects can use the same definition while storing different names.
A class definition does not create a student automatically. new constructs a particular object.
Run with javac Main.java, then java Main. The declaration inside Main keeps the helper type available to this standalone example.
Worked variation: Rename only one object. The other name remains unchanged because the objects are distinct.
Check your understanding
What to remember
A class defines the fields and methods available on its instances. Separate student objects can use the same definition while storing different names. A class definition does not create a student automatically. new constructs a particular object.
Related explanations: Java Variables, Java If Statement - Syntax and Examples, Exceptions in Java Introduction.
Supporting documentation: Official Java learning guide and Java 17 language specification.
Reaching the recap and completing the quizzes are separate milestones.