Classes, objets et empaquetage
Comprenez comment définir des classes, créer des objets et organiser votre code à l’aide de paquets en Scala.
Classes, objets et empaquetage est une leçon Scala for Backend Engineering & Functional Programming gratuite sur CoddyKit. Ceci est la leçon 1 sur 2. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Scala for Backend Engineering & Functional Programming, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Scala for Backend Engineering & Functional Programming comprend 2 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
Welcome to OOP in Scala
In this lesson, you'll dive into the heart of Object-Oriented Programming (OOP) in Scala. We'll explore how to structure your code using classes, create instances of those classes (objects), and keep everything organized with packages.
Let's start building robust and modular applications!
Classes: The Blueprints
Think of a class as a blueprint for creating objects. It defines the properties (data) and behaviors (methods) that its objects will have. Classes don't hold data themselves, but they describe what data an object can hold.
Here's a basic class definition:
class Car {
// Properties and methods go here
}Defining a Simple Class
In Scala, you define a class using the class keyword followed by its name. Let's create a simple Dog class. It doesn't do much yet, but it's a start!
Try running this empty class definition:
class Dog {
// This dog has no properties or behaviors yet
}
object Main {
def main(args: Array[String]): Unit = {
println("Dog class defined!")
}
}Creating Objects (Instances)
An object is an instance of a class. It's a real 'thing' created from the blueprint. To create an object, you use the new keyword followed by the class name.
Each object gets its own set of data, as defined by the class.
class Dog {
// Still an empty dog blueprint
}
object Main {
def main(args: Array[String]): Unit = {
val myDog = new Dog()
val yourDog = new Dog()
println("Two dog objects created!")
}
}Adding Properties to a Class
Classes can have properties (also called fields or members) that store data. You can define these in the class constructor, making them parameters when you create an object.
Let's give our Dog a name and breed:
class Dog(val name: String, val breed: String) {
// 'val' makes name and breed immutable properties
}
object Main {
def main(args: Array[String]): Unit = {
val myDog = new Dog("Buddy", "Golden Retriever")
println(s"My dog's name is ${myDog.name} and breed is ${myDog.breed}.")
}
}Adding Behavior (Methods)
Classes also define methods, which are functions that describe the object's behavior. Methods can access and modify the object's properties.
Our Dog can now bark():
class Dog(val name: String, val breed: String) {
def bark(): String = {
s"${name} says Woof!"
}
}
object Main {
def main(args: Array[String]): Unit = {
val myDog = new Dog("Max", "Labrador")
println(myDog.bark())
}
}Scala's `object` (Singletons)
In Scala, the object keyword defines a singleton. This means only one instance of it can ever exist. You don't use new to create it; you just refer to its name.
They are often used for utility methods or a single point of entry.
object MathUtils {
def add(a: Int, b: Int): Int = a + b
def subtract(a: Int, b: Int): Int = a - b
}
object Main {
def main(args: Array[String]): Unit = {
val sum = MathUtils.add(5, 3)
println(s"5 + 3 = ${sum}")
}
}Companion Objects
A companion object is an object that has the same name as a class and is defined in the same source file. They have special access to each other's private members.
- The class holds instance-specific data and methods.
- The companion object holds static-like methods or factory methods.
class Circle(val radius: Double) {
def area: Double = Circle.PI * radius * radius
}
object Circle {
// This is the companion object for the Circle class
val PI: Double = 3.14159
def apply(r: Double): Circle = new Circle(r) // Factory method
}
object Main {
def main(args: Array[String]): Unit = {
val c = Circle(5.0) // Using the apply method from companion object
println(s"Circle area: ${c.area}")
}
}Organizing Code with Packages
Packages are a way to organize your classes and objects into logical groups, preventing name collisions and improving code maintainability.
Think of them as folders for your code. The package keyword declares the package at the top of a Scala file.
package com.coddykit.animals
class Cat(val name: String) {
def meow(): String = s"${name} says Meow!"
}
// This class is now inside com.coddykit.animals packageImporting Members from Packages
To use classes or objects defined in another package, you need to import them. The import keyword makes members of a package available in your current scope.
Let's import our Cat class:
package com.coddykit.app
// Define a class in a package first for import example
package com.coddykit.animals {
class Cat(val name: String) {
def meow(): String = s"${name} says Meow!"
}
}
import com.coddykit.animals.Cat
object Main {
def main(args: Array[String]): Unit = {
val myCat = new Cat("Whiskers")
println(myCat.meow())
}
}Quick Check: Class or Object?
You've learned about classes, objects, and packages. Let's test your understanding!
Recap: Classes, Objects, Packages
Fantastic work! You've learned the fundamentals of OOP in Scala:
- Classes are blueprints defining properties and behaviors.
- Objects are instances created from classes using
new. - Scala's
objectkeyword creates singletons, useful for utilities or factories. - Companion Objects pair with classes for static-like members.
- Packages organize your code, preventing name clashes and improving structure.
Next, we'll build on this foundation by exploring inheritance and polymorphism!
Questions Fréquemment Posées
La leçon « Classes, objets et empaquetage » est-elle gratuite ?
Oui — le texte complet de « Classes, objets et empaquetage » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Scala for Backend Engineering & Functional Programming, passe à CoddyKit PRO. Le cours Scala for Backend Engineering & Functional Programming comprend 2 leçons au total.
Qu'est-ce que j'apprendrai dans « Classes, objets et empaquetage » ?
Comprenez comment définir des classes, créer des objets et organiser votre code à l’aide de paquets en Scala. Tu pratiques Scala for Backend Engineering & Functional Programming avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Scala for Backend Engineering & Functional Programming ?
Aucune expérience préalable n'est requise. Scala for Backend Engineering & Functional Programming sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 2.
Combien de temps prend la leçon « Classes, objets et empaquetage » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Scala for Backend Engineering & Functional Programming ?
Oui. Chaque leçon Scala for Backend Engineering & Functional Programming inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Classes, objets et empaquetage
- Héritage et polymorphisme