Hi, I'm learning to program in java, and I created a class called Dog, with its attributes and methods. Also create a main program that can create 4 objects of type Dog and call methods. On the screen it prints its attributes and methods of each object. But my task is that my program can again print the new characteristics of the object after changing the name of the Dog. How can I do it??
public class Perro {
String nombre;
String raza;
String tamano;
public Perro (String nombre, String raza, String tamano){
this.nombre = nombre;
this.raza = raza;
this.tamano = tamano;
}
public void caminar() {
System.out.println(nombre + " camina");
}
public void saltar() {
System.out.println(nombre + " salta");
}
public void correr(){
System.out.println(nombre + " corre");
}
public void ladrar() {
System.out.println(nombre + " ladra");
}
}
and my main program is
public class progprincp {
public static void main (String [] args){
Perro p1;
p1 = new Perro("Vovi", "Chusco", "Enorme");
System.out.println(p1.nombre);
System.out.println(p1.raza);
System.out.println(p1.tamano);
p1.caminar();
p1.saltar();
p1.correr();
p1.ladrar();
Perro p2;
p2 = new Perro("Ted", "Chusco", "pequeño");
System.out.println(p2.nombre);
System.out.println(p2.raza);
System.out.println(p2.tamano);
p2.caminar();
p2.saltar();
p2.correr();
p2.ladrar();
Perro p3;
p3 = new Perro("3.14kxu", "pokemon electrico", "medianito");
System.out.println(p3.nombre);
System.out.println(p3.raza);
System.out.println(p3.tamano);
p3.caminar();
p3.saltar();
p3.correr();
p3.ladrar();
Perro p4;
p4 = new Perro("Betún", "Boxer", "Gordito");
System.out.println(p4.nombre);
System.out.println(p4.raza);
System.out.println(p4.tamano);
p4.caminar();
p4.saltar();
p4.correr();
p4.ladrar();
}
To be able to change the name, the ideal is to create the get and set functions in their respective attributes, these functions can be created automatically in some IDEs, for example I use NetBeans and Alt+Insert is created and I select getter and setter and it creates them automatically .
This is how the dog class would look like, it is not necessary to create all the functions if you are not going to use them. The main class would look like this
The setName function is the one in charge of giving it a new name, and you only print everything again. I hope this helps you. Cheers