Bird
0
0

Which of the following correctly defines a parameterized constructor for the class Animal with fields species and age?

easy📝 Syntax Q3 of 15
Java - Constructors

Which of the following correctly defines a parameterized constructor for the class Animal with fields species and age?

class Animal {
  String species;
  int age;
  // Constructor here
}
Apublic void Animal(String species, int age) { this.species = species; this.age = age; }
Bvoid Animal(String s, int a) { species = s; age = a; }
CAnimal() { species = ""; age = 0; }
DAnimal(String species, int age) { this.species = species; this.age = age; }
Step-by-Step Solution
Solution:
  1. Step 1: Identify constructor syntax

    A constructor has no return type and matches the class name.
  2. Step 2: Check options

    Animal(String species, int age) { this.species = species; this.age = age; } correctly defines a constructor with parameters and assigns values using this.
  3. Final Answer:

    Animal(String species, int age) { this.species = species; this.age = age; } -> Option D
  4. Quick Check:

    Constructor must have no return type and match class name [OK]
Quick Trick: Constructor has no return type and matches class name [OK]
Common Mistakes:
  • Adding a return type to constructor
  • Using void keyword with constructor
  • Not matching constructor name with class name

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes