LearnFrenzy
Sign in Take a free test

Classes and Objects · Find the Error · Question 6

Error: assigning an object to an unrelated type Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links