Writing a class: fields, constructor, methods · Escribir una clase: campos, constructor, métodos
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).
Crea tu propio tipo
- Hasta ahora has utilizado clases como
StringyMathque te proporcionó Java. - Ahora vas a escribir tu propia clase. Una clase es un plano para un objeto.
- Un objeto contiene datos (sus propios valores) y métodos (cosas que puede hacer).
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 de instancia
- Los datos que cada objeto conserva se almacenan en variables de instancia (también llamadas campos).
- Se declaran dentro de la clase, pero fuera de cualquier método.
- Cada objeto obtiene su propia copia de estas 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 constructor
- Un constructor configura un nuevo objeto. Se ejecuta cuando escribes
new. - Tiene el mismo nombre que la clase y no tiene tipo de retorno (ni siquiera
void). - Usa la palabra
thispara referirse a "la variable propia de este objeto".
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étodos de instancia
- Un método de instancia es una acción que un objeto puede realizar.
- Puede leer y modificar las variables de instancia del objeto.
- Se llama sobre un objeto usando un punto:
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.
Crear y usar un objeto
- Usa
new ClassName(...)para construir un objeto. Esto invoca al constructor. - Guárdalo en una variable cuyo tipo sea el nombre de la clase.
- Luego llama a sus métodos con un punto.
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.
¿Por qué this?
- Un parámetro y un campo pueden tener el mismo nombre (como
name). - Dentro del constructor,
namesignifica el parámetro;this.namesignifica el campo. thissiempre significa el objeto sobre el cual se llamó al método.
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.
Errores comunes
- Un constructor no tiene tipo de retorno y coincide con el nombre de la clase.
- Usa
this.fieldpara diferenciar un campo de un parámetro con el mismo nombre.
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.
Ahora tú lo intentas
- Cada tarea te ofrece un esqueleto de clase con un TODO. Rellénalo para que compile y funcione.
- Un Harnés oculto construye tu objeto y comprueba los resultados.
- Pulsa Run para compilar, luego Check answer.
Complete the Counter class. It has an int field · campo count that starts at 0. increment() adds 1 to it. getCount() returns the current value. · Completa la clase Counter. Tiene un campo int llamado count que comienza en 0. increment() le suma 1. getCount() devuelve el valor actual.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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). · Completa la clase Rectangle. El constructor toma ancho w y alto h y los almacena. area() devuelve ancho por alto. perimeter() devuelve 2 veces (ancho más alto).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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!). · Completa la clase Greeter. El constructor toma un String name y lo almacena en el campo name. greet() devuelve el texto Hello, seguido del nombre y un ! (para "Ana" devuelve Hello, Ana!).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.