B a=new A(),A是父类,B是子类,为什么不能这么写,系统提示的错误是Type mismatch: cannot convert from A to B,这是一个类型转换的过程吗,求解 求解
------解决思路----------------------
举个例子:
java中所有的类 的超类都是Object
难道 new Object(); 的 引用能随便使用一个 子类的引用吗?
例如 : String str = new Object(); 这肯定不对呀
------解决思路----------------------
你或许没有理解继承的含义;
例如:
图形是个类,矩形、三角形是它的子类;
你可以说矩形、三角形是图形,而不能反过来吧;
------解决思路----------------------
理解有误呀!
在生活中都说儿子长的像爹,有人说爹长的像儿子吗
------解决思路----------------------
B which is subclass of class A often carries more features besides those extends from A, in other words,A is subset of B.
= is an assignment symbol which requires the right side at least owns the whole features of the class on the left side.
Therefore,A a = new B() is correct whereas B b = new A() will fail to pass the compilation.
More vivid example, let us suppose that you need a book, your friend offer you a sheet of paper.Obviously your requirement cannot be catered,although a sheet of paper is a part of a book.But if your friend offer you a book and a sheet of paper.S/he can cater you. Perhaps it's not a suitable example, but it can make you easy to understand this question.
------解决思路----------------------
B a=B(new A())
可以这么写 ,这样只能调用父类有的方法 ,子类中自己的方法是不能被调用的。