Search code examples
javaswinginstancejtextfieldextending

Why can't a class extending JTextField instantiate a JPasswordField?


I have an empty class MyJTextField extending JTextField, and I want MyJTextField to be initialized as JPasswordField, like JTextField can do.

JTextField pass = new JPasswordField(); //no errors
but
MyJTextField pass = new JPasswordField();//"Type mismatch: cannot convert from JPasswordField to MyJTextField"

Solution

  • Your MyJTextField is a child of JTextField. And JPasswordField also is a child of JTextField. But MyJTextField is not a child of JPasswordField, so MyJTextField is not a JPasswordField, they are siblings.

        //you can do
        JTextField field1 = new JPasswordField(); //child is an instance of parent
        JTextField field2 = new MyJTextField(); //child is an instance of parent
    
        //you can't do
        JPasswordField field3 = new JTextField(); // parent is not instance of child
        MyJTextField field4 = new JTextField(); // parent is not instance of child
        JPasswordField field5 = new MyJTextField(); // siblings are not instances of each other
        MyJTextField field6 = new JPasswordField(); // siblings are not instances of each other