Question 6
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
class Dog { String name = "Tommy"; }
class Cat { String name = "Kitty"; }
public class Main {
public static void main(String[] args) {
Dog d = new Cat();
System.out.println(d.name);
}
}
- A name must be private
- B Cat is not a Dog (the classes are unrelated), so a Cat object cannot be assigned to a Dog variable Correct
- C Dog needs a constructor
- D Fields cannot have default values
Correct Answer: Option B
Assignment works only to the same type or a supertype (see Inheritance).
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!