Publi

Numerar objetos de una clase determinada [Java]

Hace un tiempo comentaba esto mismo en lenguaje C++, aunque por el motivo de las clases particulares, a algunos les interesaba más el tema en Java, aunque es muy parecido, tenemos que crear un atributo estático y coger su valor cada vez que instanciemos la clase.

Como hice en C++, planteamos este problema como un almacén de clientes (es un ejemplo, no vale si tenemos muchos clientes, ya usaríamos bases de datos, por ejemplo). Cada vez que se construye un cliente, éste obtendrá un número de cliente (incremental) automáticamente.

De la siguiente manera:

Cliente.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Cliente
{

    private static int cuentaClientes=0;
    private int numCliente;
    private String nombre;

    public Cliente(String nombre)
    {
    this.nombre=nombre;
    this.cuentaClientes++;
    this.numCliente=this.cuentaClientes;
    }

    public String toString()
    {
    return "Soy "+this.nombre+" y mi número es "+this.numCliente;
    }
}

Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main
{
    public static void main(String[] params)
    {
    Cliente c1 = new Cliente("Alfredo");
    Cliente c2 = new Cliente("Adolfo");
    Cliente c3 = new Cliente("Alejadro");
    Cliente c4 = new Cliente("Alfonso");

    System.out.println(c1.toString());
    System.out.println(c2.toString());
    System.out.println(c3.toString());
    System.out.println(c4.toString());
    }
}

Compilamos con:

$ javac Main.java Cliente.java

O con nuestro IDE preferido, y su salida debe ser:

Soy Alfredo y mi número es 1
Soy Adolfo y mi número es 2
Soy Alejadro y mi número es 3
Soy Alfonso y mi número es 4

También podría interesarte....

There are 4 comments left Ir a comentario

  1. Pingback: Bitacoras.com /

  2. Pingback: BlogESfera.com /

  3. Andrew Mark /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    Your post is very helpful and information is reliable. I am satisfied with your post. Thank you so much for sharing this wonderful post.
    Carmy Jacket The Bear

  4. seo /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    Interesting topic for a blog. I have been searching the Internet for fun and came upon your website.This is really nice to read..informative post is very good to read..thanks a lot!I really loved reading your blog. It was very well authored and easy to undertand. Unlike additional blogs I have read which are really not tht good. I also found your posts very interesting. In fact after reading, I had to go show it to my friend and he ejoyed it as well!I learn some new stuff from it too, thanks for sharing your information. https://www.digitekprinting.com/

Leave a Reply