Beginner level · Module 4: Classes and Objects in Java · Lesson 1 of 3
Your First Class
Define a class with fields and methods, create objects with new, and call methods on them.
In this lesson you will
- Explain the difference between a class and an object
- Write a class with fields and instance methods and create objects from it
Key concepts
classobjectfieldinstance method
The lesson
A class is a blueprint; an object is one thing built from it. A Product class can describe that every product has a name and a price, while new Product() creates one particular product in memory.
Fields store each object's data and instance methods work with that data. Two Product objects have separate copies of name and price, so changing one does not affect the other.
Override toString() to control how an object prints. Without it, printing an object shows something like Product@1b6d3586, which is not useful to anyone reading the output.
Step by step
- Create a class Product with fields name and price.
- Add a method describe() that returns a sentence about the product.
- In main, create two Product objects and call describe() on each.
- Override toString() and print the objects directly.
Practice activity
Write a Student class with name, school and three marks, and a method average(); create three students and print their averages.
Expected result: Each student prints its own average, showing that objects keep separate data.
Check your understanding
-
What keyword creates a new object?
Show answer
new
-
Why override toString()?
Show answer
So that printing an object shows useful information instead of the class name and a hash code.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.