[英]Why B b = new A() is invalid and A a = new B() is valid when B extends A?
I am new to JAVA and want to know that why 我是JAVA的新手,想知道为什么
A a = new B();
is valid and 有效且
B b = new A();
is invalid Considering that: 考虑到以下因素是无效的:
class A;
class B extends A;
Because B
, by extending A
, is also an A
. 因为
B
通过扩展A
也是A
We say this in object-orientation terms by saying that a B
is-a A
. 我们用面向对象的术语说
B
是 A
This means that you can use a B
anywhere you use an A
. 这意味着,你可以使用
B
任何你使用A
。
This relationship is not commutative -- B
is-a A
does not imply that A
is-a B
. 这种关系是不可交换-
B
is-a的A
并不意味着A
是-A B
。 Therefore you cannot use an A
anywhere you would use a B
. 因此,你不能使用
A
任何地方,你会用B
。
Consider this case: 考虑这种情况:
class Animal;
class Dog extends Animal;
This makes sense: 这是有道理的:
Animal animal = new Dog();
Anywhere it makes sense to use an Animal
you can also use a Dog
. 在任何可以使用
Animal
也可以使用Dog
。 This is intuitive. 这很直观。
Dog dog = new Animal();
This, on the other hand, does not make sense. 另一方面,这是没有意义的。
Because when B extends A you consider that every B is a more complex A, using the attributes and methods from A and adding some of his own, but an A cannot be a B, there could be methods in B not specified in A, and as it is not extended from B, cannot be instantiated. 因为当B扩展A时,您会认为每个B都是更复杂的A,使用A的属性和方法并添加他自己的一些属性,但是A不能是B,因此B中可能存在未在A中指定的方法,并且因为它不是从B扩展的,所以无法实例化。
Every B is an A , but no every A is a B ( unless you specify that ) 每个B都是A,但是每个A都不是B(除非您指定)
class A {
int i = 10;
}
class B {
int i = 10;
int j = 20;
}
class C {
public static void main(String args[]){
B b;
B b=new A();
System.out.println(b.j);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.