为什么扩展JTextField的类不能实例化JPasswordField?

时间:2017-01-28 16:09:15

标签: java swing instance jtextfield extending

我有一个空类 MyJTextField 扩展 JTextField ,我想将MyJTextField初始化为 JPasswordField ,就像JTextField一样。

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

1 个答案:

答案 0 :(得分:1)

您的MyJTextField是JTextField的子级。而JPasswordField也是JTextField的孩子。但MyJTextField不是JPasswordField的子代,因此MyJTextField不是JPasswordField,它们是兄弟姐妹。

    //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