【发布时间】:2015-07-05 14:34:58
【问题描述】:
我正在为 Java 中最基本的 OOP 概念而苦苦挣扎。
class Person {}
class Parent extends Person {}
所有的父母都是人,但不是所有的人都是父母。
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 表达成为子类的想法?是否只需要为接受超类对象的子类编写一个构造函数...
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-s 是 S 和 T 的实例,而 v 的使用是有效,因为 S 是 T 的子类。
我的问题是我的方法是否正确?
【问题讨论】:
-
你的论点有道理。我认为这是正确的方式
-
如果您的模型要求一个对象从一般的
X(例如Person)开始,然后变成更具体的Y(例如Parent),那么它可能不是使用继承的好情况,因为正如您所观察到的,您无法在运行时更改对象的类型。 -
对象不会变成任何东西,只是是。
-
@Themanontheclapham 可怜的亚当仍然不能成为
Parent,除非你告诉它是Parent(通过演员表)。 -
@khelwood - 有没有更合适的特定设计模式?
标签: java oop inheritance