我在线学习初学者java课程,我需要更好地理解作业如何与继承一起工作。 例如,如果我有这些类......
public class Cell{...}
public class BloodCell extends Cell {...}
public class RedBloodCell extends BloodCell {...}
这些有效吗?
Cell c = new BloodCell();
Cell c = new RedBloodCell();
BloodCell c = new RedBloodCell();
RedBloodCell c = new BloodCell();
答案 0 :(得分:1)
extends
用于继承,在外行术语中它类似于“is-a”属性
所以A类扩展了其他一些B类,意味着“A类是-B类”。 换句话说,B类是A类的父母。
父类引用可以包含子对象,反之亦然。
Cell c = new BloodCell(); // OK, as BloodCell is a Cell,
Cell c = new RedBloodCell(); // OK, RedBloodCell is a Cell
BloodCell c = new RedBloodCell(); // OK, RedBloodCell is a BloodCell
RedBloodCell c = new BloodCell(); // ERROR, BloodCell is not a RedBloodCell
答案 1 :(得分:0)
Cell c = new BloodCell(); //OK: all blood cells are cells
Cell c = new RedBloodCell();//OK: all red blood cells are cells
BloodCell c = new RedBloodCell();//OK: all red blood cells are blood cells
RedBloodCell c = new BloodCell();//ERROR: not all blood cells are red blood cells