Writing a class: fields, constructor, methods · Écrire une classe : champs, constructeur, méthodes
Make your own type
- So far you used classes like
StringandMaththat Java gave you. - Now you will write your own class. A class is a plan for an object.
- An object holds data (its own values) and methods (things it can do).
Créer votre propre type
- Jusqu'à présent, vous avez utilisé des classes comme
StringetMathque Java vous a données. - Maintenant, vous allez écrire votre propre classe. Une classe est un plan pour un objet.
- Un objet contient des données (ses propres valeurs) et des méthodes (ce qu'il peut faire).
Instance variables
- Data that each object keeps is stored in instance variables (also called fields).
- You declare them inside the class, but outside any method.
- Each object gets its own copy of these variables.
Variables d'instance
- Les données que chaque objet conserve sont stockées dans des variables d'instance (aussi appelées champs).
- Vous les déclarez à l'intérieur de la classe, mais hors de toute méthode.
- Chaque objet obtient sa propre copie de ces variables.
public class Dog {
String name; // instance variable
int age; // instance variable
}
A constructor
- A constructor sets up a new object. It runs when you write
new. - It has the same name as the class and no return type (not even
void). - Use the word
thisto mean "this object's own variable".
Un constructeur
- Un constructeur met en place un nouvel objet. Il s'exécute lorsque vous écrivez
new. - Il a le même nom que la classe et aucun type de retour (pas même
void). - Utilisez le mot
thispour signifier "la variable propre à cet objet".
public class Dog {
String name;
int age;
// Constructor: runs when we make a new Dog
public Dog(String name, int age) {
this.name = name; // this.name is the field; name is the parameter
this.age = age;
}
}
Instance methods
- An instance method is an action an object can do.
- It can read and change the object's own instance variables.
- You call it on an object with a dot:
myDog.speak().
Méthodes d'instance
- Une méthode d'instance est une action qu'un objet peut effectuer.
- Elle peut lire et modifier les variables d'instance propres à l'objet.
- Vous l'appellez sur un objet avec un point :
myDog.speak().
public class Dog {
String name;
int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
// Instance method: returns a sentence about this dog
public String describe() {
return this.name + " is " + this.age;
}
}
Make and use an object
- Use
new ClassName(...)to build an object. This calls the constructor. - Store it in a variable whose type is the class name.
- Then call its methods with a dot.
Créer et utiliser un objet
- Utilisez
new ClassName(...)pour construire un objet. Cela appelle le constructeur. - Stockez-le dans une variable dont le type est le nom de la classe.
- Ensuite, appelez ses méthodes avec un point.
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex", 4);
System.out.println(d.describe()); // Rex is 4
}
}
class Dog {
String name;
int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String describe() {
return this.name + " is " + this.age;
}
}
Why this?
- A parameter and a field can have the same name (like
name). - Inside the constructor,
namemeans the parameter;this.namemeans the field. thisalways means the object the method was called on.
Pourquoi this ?
- Un paramètre et un champ peuvent avoir le même nom (comme
name). - À l'intérieur du constructeur,
namesignifie le paramètre ;this.namesignifie le champ. thissignifie toujours l'objet sur lequel la méthode a été appelée.
Common mistakes
- A constructor has no return type and matches the class name.
- Use
this.fieldto tell a field from a parameter of the same name.
Erreurs courantes
- Un constructeur n'a pas de type de retour et correspond au nom de la classe.
- Utilisez
this.fieldpour distinguer un champ d'un paramètre de même nom.
Now you try
- Each task gives you a class skeleton with a TODO. Fill it in so it compiles and works.
- A hidden Harness builds your object and checks the results.
- Press Run to compile, then Check answer.
À vous maintenant
- Chaque exercice vous donne une structure de classe avec un TODO. Remplissez-le pour qu'il compile et fonctionne.
- Un Harness caché construit votre objet et vérifie les résultats.
- Appuyez sur Run pour compiler, puis sur Check answer.
Complete the Counter class. It has an int field · champ count that starts at 0. increment() adds 1 to it. getCount() returns the current value. · Complétez la classe Counter. Elle a un champ int count qui commence à 0. increment() ajoute 1 à celui-ci. getCount() retourne la valeur actuelle.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Complete the Rectangle class. The constructor takes width w and height h and stores them. area() returns width times height. perimeter() returns 2 times (width plus height). · Complétez la classe Rectangle. Le constructeur prend width w et height h et les stocke. area() retourne width multiplié par height. perimeter() retourne 2 fois (width plus height).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Complete the Greeter class. The constructor takes a String name and stores it in the field name. greet() returns the text Hello, followed by the name and a ! (for "Ana" it returns Hello, Ana!). · Complétez la classe Greeter. Le constructeur prend un String name et le stocke dans le champ name. greet() retourne le texte Hello, suivi du nom et d'un ! (pour "Ana" il retourne Hello, Ana!).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.