java - 超类 obj = 新子类();意义和铸造
问题描述
如果我有超类(动物)和子类(猫)。
第三点是什么意思?什么时候我们必须施放?
Cat obj = new Cat();
意味着从 Cat 类创建一个对象Animal obj = new Animal();
意味着从 Animal 类创建一个对象Animal obj = new Cat();
解决方案
首先让我们了解类、引用和对象。假设我们有一个名为SomeClass
SomeClass ref = new SomeClass();
上面我们在堆中创建了一个 SomeClass 的对象,并且引用变量引用了它。我们将引用变量命名为ref
。对象存在于堆中,我们可以使用引用访问它。所以对象类型是实际的类(new
已应用关键字)。引用变量类型可以是实际类或其父类。
现在让我们看看继承的关系。从另一个类继承的类共享子-父关系。Child 继承其 Parent 的行为,然后可以覆盖一些行为,也可以添加一些额外的行为。因此,子对象可以在预期父对象的任何地方使用,因为子对象具有其父对象的所有行为,因此调用父对象中存在的任何行为都将由子对象处理。
父类不知道其子类的附加行为(子类是稍后编写的。)因此,父类的对象不能在预期有子类对象的地方使用(如果在父类上调用了子类的附加行为反对,则不会兑现)。
现在让我们假设我们有类ParentClass
,ChildClass
这样ChildClass inherits ParentClass
ParentClass reference = new ParentClass(); // Valid
ParentClass reference = new ChildClass(); //Valid
ChildClass reference = new ChildClass(); //Valid
ChildClass reference = new ParentClass();// Not Valid.
注意 ParentClass 参考 = new ChildClass(); // 这里 Object 是 ChildClass 类型,Reference 是 ParentClass 类型。
现在什么时候投。任何期望 ParentClass 对象的地方,都不需要强制转换,(ParentClass 或 ChildClass 的)对象都可以。任何期望 ChildClass 类型的对象的地方,但如果我们有如下情况,则需要强制转换。
public void someMethod(ChildClass expected){
//some implementation
}
ParentClass ref = new ChildClass();
someMethod(ref);//Invalid : Compilation Issue
someMethod((ChildClass)ref);// Valid
ParentClass anotherRef = new ParentClass();
someMethod(anotherRef); // Invalid : Compilation Issue
someMethod((ChildClass)ref); //Invalid, compiles but Runtime it will fail.
拇指规则:孩子是孩子,孩子是父母,父母是父母,父母不是孩子。
另一个理解的例子。
public abstract class List{
public abstract void add(int element);
public abstract void remove(int element);
public int size();
}
public class Application{
private List listReference;
public void setList(List ref){
listReference = ref;
}
}
//Now you may create sub classes as below
public class ArrayList extends List{
// all the abstract methods of List have been implemented
}
public class LinkedList extends List{
//all the abstract methods of List have been implemented
}
现在在 main 方法中,您可以传递 ArrayList 或 LinkedList 或任何其他实现。
public class Init{
public static void main(String[] args){
Application app = new Application ();
app.setList(new LinkedList());
//or you can set it like this
List listRef = bew ArrayList();
app.setList(listRef);
//or you can set it like this
LinkedList linkedListRef = new LinkedLiet();
app.setList(linkedListRef);
}
}
请注意,该方法setList()
接受 List 类型的引用,我们可以提供 List 抽象的任何实现。这导致了灵活的设计。类应该依赖于抽象。接口编程是一种设计原则,它使应用程序代码易于维护。
推荐阅读
- html - 即使在具有引导程序的较小设备上,如何使项目保持一致
- java - 使用ajax调用在django中添加搜索数据的分页
- animation - 无损视频压缩格式
- c# - 可以在 Visual Studio 控制台/Windows 应用程序中安装和使用实体框架
- visual-studio - 请求中止:无法在 VS 2019 中为“https://api.nuget.org/v3/index.json”创建 SSL/TLS 安全通道
- regex - 将vim中的十进制数乘以固定数量
- javascript - 弹窗第二次未触发
- node.js - 在嵌套数组中比较并添加两个数组
- rust - 如何从迭代器循环内部跳过 n 个项目?
- python - 如何使用 pandas 数据框的特定行和列创建新系列?