简体   繁体   English

当B扩展A时,为什么B b = new A()无效而A a = new B()有效?

[英]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.

相关问题 新列表<A & ? extends B>();</a> - new List<A & ? extends B>(); 当&#39;B&#39;延伸&#39;A&#39;时,为什么要实现接口&#39;A&#39;和&#39;B&#39; - Why implement interfaces 'A' and 'B', when 'B' extends 'A' 道具(新A与B)和道具[A与B]之间的区别 - Differences between Props(new A with B) and Props[A with B] 为什么“a ^ = b ^ = a ^ = b;”不同于“a ^ = b; b ^ = A;一个^ = B;”? - Why is “a^=b^=a^=b;” different from “a^=b; b^=a; a^=b;”? <A><B>当B扩展A时,</a>从列表转换<A>为列表</a> - Cast from List<A> to List<B> when B extends A 差异图 <A,B> foo =新的HashMap <A,B> ()和新的HashMap &lt;&gt;()? - Difference Map<A,B> foo = new HashMap<A,B>() and new HashMap<>()? 为什么\\ B有效但\\ b不起作用 - why does \B works but not \b 如果B扩展了A,则不能将List强制转换<A>为List <B>(很有意义),但是为什么一个可以将List强制转换</a> <? extends A> <A><B>列出<B>?</a> - If B extends A, one cannot cast List<A> to List<B> (makes sense), but then why can one cast List<? extends A> to List<B>? A obj = new A(new B); 是什么意思? - Whats the meaning of A obj = new A(new B);? 当您执行A事情= new B()时,实例变量调用如何工作? 其中B是A的子类? - How does instance variable invocation work when you do A thing = new B(); where B is a subclass of A?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM