Classes, objetos e empacotamento
Compreenda como definir classes, criar objetos e organizar seu código usando pacotes em Scala.
Classes, objetos e empacotamento é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 1 de 2. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Scala for Backend Engineering & Functional Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Scala for Backend Engineering & Functional Programming inclui 2 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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!
Perguntas Frequentes
A aula “Classes, objetos e empacotamento” é grátis?
Sim — o texto completo de “Classes, objetos e empacotamento” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Scala for Backend Engineering & Functional Programming, atualize para CoddyKit PRO. O curso de Scala for Backend Engineering & Functional Programming inclui 2 aulas no total.
O que vou aprender em “Classes, objetos e empacotamento”?
Compreenda como definir classes, criar objetos e organizar seu código usando pacotes em Scala. Você pratica Scala for Backend Engineering & Functional Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Scala for Backend Engineering & Functional Programming?
Nenhuma experiência prévia é necessária. Scala for Backend Engineering & Functional Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 2.
Quanto tempo leva a aula “Classes, objetos e empacotamento”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Scala for Backend Engineering & Functional Programming?
Sim. Cada aula de Scala for Backend Engineering & Functional Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Classes, objetos e empacotamento
- Herança e polimorfismo