Course Content
Java Extended
Java Extended
Challenge














Task
There is a class called Parrot
that already has all the fields and a constructor defined. In the main
method, three different parrots are created, and then I attempt to print each of them on the screen. However, it only displays the hash code and the class name.
Your task is to write a toString()
method that will display all the information about the parrot.
Main.java
- 1. Use the syntax that you prefer. Here's my advice;
- 2. Start by writing the class name and open a square bracket:
"Parrot {"
; - 3. Then, go through the fields in order. Begin with the parrot's name:
"name=' " + name + " ' "
;- 4. Continue going through the fields in order:
", age= " + age"
; - 5. When you reach the last field, close the square bracket:
`"}"
; - 6. Feel free to adjust the syntax based on your preference.
- 2. Start by writing the class name and open a square bracket:
package com.example;
class Parrot {
String name;
int age;
String color;
boolean canParrotTalk;
@Override
public String toString() {
return "Parrot{" +
"name='" + name + "'" +
", age=" + age +
", color='" + color + "'" +
", canParrotTalk=" + canParrotTalk +
'}';
}
public Parrot(String name, int age, String color, boolean canParrotTalk) {
this.name = name;
this.age = age;
this.color = color;
this.canParrotTalk = canParrotTalk;
}
}
public class Main {
public static void main(String[] args) {
Parrot bubba = new Parrot("Bubba", 1, "Yellow", true);
Parrot rio = new Parrot("Rio", 3, "Blue", false);
Parrot ollie = new Parrot("Ollie", 2, "Red", true);
System.out.println(bubba);
System.out.println(rio);
System.out.println(ollie);
}
}














Everything was clear?
Section 4. Chapter 9