gpt4 book ai didi

Java - 将通用类的实例转换为专用类的实例

转载 作者:行者123 更新时间:2023-11-30 06:13:54 25 4
gpt4 key购买 nike

我正在为 Java 中最基本的 OOP 概念而苦苦挣扎。

class Person {}

class Parent extends Person {}

所有的 parent 都是人,但不是所有的人都是 parent 。

Person adam  = new Person();
adam = new Parent(); // but this just means that the variable 'adam' is just referencing a completely new object.
adam = (Parent)adam; // java.lang.ClassCastException

在 Java 中如何表达成为子类的想法?是否只需要为采用父类(super class)对象的子类编写一个构造函数...

public class Person {

private String name;

public Person(String name){
this.name = name;
}

public String getName() {
return this.name;
}

}

现在父类看起来像:

public class Parent extends Person {
public Parent(Person p) {
super(p.getName());
}
}

输出:

public class Run {

public static <T> void display(T x) {
System.out.println(x);
}

public static void main(String[] args) {

Person adam = new Person("adam");

display(adam instanceof Person); // true
display(adam instanceof Parent); // false

// now lets assume that adam has had a child.
// adam has 'become' a parent. He is still also a person.

adam = new Parent(adam);

display(adam instanceof Person); // true
display(adam instanceof Parent); // true
}
}

这是唯一的方法吗?有没有更好的方法?如何在 Java 中表达成为的想法。也就是说,从对通用对象的引用开始,然后变得更加特化。

** 编辑澄清:

假设我们有一个类 T

假设我们有一个T类型的变量v (v::T)

我们将 v 设置为引用类型为 T 的新对象。

T v = new T();

(v::T) -> (obj-t::T)

我们有一个 S 类,它是 T 类型的子类。它可能有也可能没有额外的方法。

我想创建一个类型为 S 的新对象 obj-s,它从 obj-t

允许我使用现有变量 (v::T) 来引用新对象。

v = new S(v);

(v::T) -> (obj-s::S)

因此 obj-sST 的实例,v 的使用是有效,因为 ST 的子类。

我的问题是我的方法是否正确?

最佳答案

这在 Java 中是不可能的。一旦一个对象被创建为某种类型,它在其剩余的生命周期中将保持该类型。因此,如果您创建一个 Parent,您可以将其称为 ObjectPersonParent ,但在它下面始终是一个Parent,并且在对象创建后不能更改。

关于Java - 将通用类的实例转换为专用类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31231432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com