What is a class and an object in Java?
A class is a blueprint which describes the data (fields) and the actions (methods). An object is a real thing made from the class with new. Many objects can be made from one class, each with its own data.
class Car {
String model;
int speed;
void accelerate() {
speed += 10;
}
}
public class Main {
public static void main(String[] args) {
Car c1 = new Car();
c1.model = "Swift";
c1.accelerate();
c1.accelerate();
Car c2 = new Car();
c2.model = "Creta";
System.out.println(c1.model + " " + c1.speed);
System.out.println(c2.model + " " + c2.speed);
}
}
Output
Swift 20
Creta 0
Learn more about the similar topics:
| Tutorials |
|---|
| Java Classes and Objects |
| Java Constructors |
| Java static and this Keywords |
| Java Encapsulation and Access Modifiers |
| Java Inheritance |
| Java Polymorphism |
| Java Abstract Classes |
| Exercises & Assignments |
|---|
| Build a BankAccount class |
| Calculate areas with inheritance and polymorphism |
| Use a sealed interface and pattern matching |