Challenge: Animal Information Display
Opgave
Swipe to start coding
Your task is to bypass the private
access modifier and create two objects with the necessary parameters, then display them.
- Create two objects of the
Animal
class — one for a cat and one for a dog.- You need to create an object
cat
of theAnimal
class with the type "Cat", name "Garfield", and color "Red". - You also need to create an object
dog
of theAnimal
class with the type "Dog", name "Maks", and color "Black".
- You need to create an object
- Create and use the
Animal(String type, String name, String color)
constructor to pass the parameterstype
,name
, andcolor
for each object. - After creating the objects, use
System.out.println()
to print information about each animal.
Løsning
solution.java
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.example;
public class Main {
public static void main(String[] args) {
Animal cat = new Animal("Cat", "Garfield", "Red");
System.out.println(cat);
Animal dog = new Animal("Dog", "Maks", "Black");
System.out.println(dog);
}
}
class Animal {
private String type;
private String name;
private String color;
public Animal(String type, String name, String color) {
this.type = type;
this.name = name;
this.color = color;
}
@Override
public String toString() {
return "Animal{" + "type='" + type + '\'' + ", name='" + name + '\'' + ", color='" + color + '\'' + '}';
}
}
Var alt klart?
Tak for dine kommentarer!
Sektion 5. Kapitel 4
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.example;
public class Main {
public static void main(String[] args) {
// You should write your solution here.
}
}
class Animal {
private String type;
private String name;
private String color;
@Override
public String toString() {
return "Animal{" + "type='" + type + '\'' + ", name='" + name + '\'' + ", color='" + color + '\'' + '}';
}
}
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat