Java
Summary - Classes
Combine attributes and methods to write a User class.
Summary - Classes
In this group you learned to define a class, add fields and methods, instantiate with new and print objects readably with toString. A class consists of a name, fields and methods. Instances are independent; each carries its own data.
Now you will bring it all together: define a class, add fields and a method, create an instance and print it with toString. This is the cornerstone of object-oriented programming; later, constructors, inheritance and interfaces will build on this foundation.
Exercise Define the Car class with toString
Define a class named Car. Add String brand and int year fields. Add a void start() method; its body writes System.out.println(brand + " started");. Add a public String toString() method returning brand + " " + year. In main create a Car instance, assign values to the fields, call the start method and print the instance with println.
Show example solution
class Car {
String brand;
int year;
void start() {
System.out.println(brand + " started");
}
public String toString() {
return brand + " " + year;
}
public static void main(String[] args) {
Car c = new Car();
c.brand = "Toyota";
c.year = 2024;
c.start();
System.out.println(c);
}
}
What comes next?
You learned the basic class structure. In the next groups you will use constructors to initialize fields, inheritance to share code between classes and interfaces to define contracts.
This group combined field declaration, method definition, instantiation with new and overriding toString. These are the core of object-oriented Java. Next you will explore a cleaner way to set initial values with constructors; instead of assigning fields by hand, you will create instances with a constructor call.
Exercise Define the Student class
Define a class named Student. Add String name and int grade fields. Add a public String toString() method returning name + " - " + grade. In main create two Student instances, assign different values and print both with println.
Show example solution
class Student {
String name;
int grade;
public String toString() {
return name + " - " + grade;
}
public static void main(String[] args) {
Student a = new Student();
a.name = "Alex";
a.grade = 90;
Student b = new Student();
b.name = "Sam";
b.grade = 85;
System.out.println(a);
System.out.println(b);
}
}
Test yourself
-
Two instances are created from a class. Their fields hold different values. What does this show?
- The fields are static
- The instances are independent
- The class is wrongly defined
- toString is missing
Show answer
The instances are independent — The instances are independent — each carries its own field value.
-
Complete the instantiation line
Car c = ____;
c.start();
Show answer
Car c = new Car();
c.start();
Next lesson: Constructor basics