【问题标题】:Instancing a class with different constructor用不同的构造函数实例化一个类
【发布时间】:2020-09-16 19:59:26
【问题描述】:

假设我有一个名为 class1 的类和一个扩展它的类 class2。我想了解下一行在实例化类对象时意味着什么

class1 classObjectName = new class2();

我知道我正在使用class2 的构造函数,但我的问题是,如果我将使用任一类中的方法,这条线将如何影响方法的使用

还有

class1 classObjectName = new class1();

class1 classObjectName = new class2();

我的问题是在这两行之后创建了多少个实例,是来自 class1 还是 class2?

谢谢

【问题讨论】:

  • 吹毛求疵:Java 命名约定中的类以大写字母 (Class1) 开头。
  • 如果您实例化 ClassChild 并将其分配给 ClassParent 的变量,它会生成 ClassParent 类型的结果变量。这意味着在 ClassChild 中声明的任何方法都将不可用,因为编译器将其视为 ClassParent 类型。
  • 所以如果我理解正确,我已经实例化了 2 个对象 class1 和 class2 对吗? class1 是 class1 和 class2 的类型 class

标签: java object constructor


【解决方案1】:

我整理了一个例子来展示一些行为。当分配为父级时,子级实例将失去对其子级特定方法和数据的访问权限,但会保留数据。这意味着如果您将其转换回 Child,它将再次用作 Child。

主要:

public class Main
{

  public static void main(String[] args)
  {
    ClassParent parent = new ClassChild("Child");
    
    parent.ChildMethod(); //Compiler Error
    System.out.println("Value: " + parent.childValue); //Compiler Error

    //Still an instance of ClassChild even if seen as a ClassParent by the compiler
    System.out.println("Child Instance: " + (parent instanceof ClassChild)); //true
    
    ClassChild child = (ClassChild) parent;
    
    child.ChildMethod(); //No Error
    System.out.println("Value: " + child.childValue); //Retains child variable data
  }
}

家长:

public class ClassParent
{
   
}

孩子:

public class ClassChild extends ClassParent
{
  public String childValue;
  
  public ClassChild(String value)
  {
    childValue = value;
  }
  
  public void ChildMethod()
  {
    
  }
}

【讨论】:

  • 非常感谢您的详细说明。对于我的另一个问题,我将从您制作的示例中获取。ClassParent parent = new ClassChild("Child"); 在该行中,实例是来自 ClassChild 还是 ClassParent ?
  • @AmrMahmoud 它仍然是 ClassChild 的实例,但编译器将其视为 ClassParent。这就是为什么它在尝试访问 ClassChild 方法/数据时抛出错误但仍保留该数据,允许将其转换回 ClassChild。这也是您可以使用 instanceof 运算符将其识别为实际 ClassChild 的原因。
  • @AmrMahmoud 我在 Main 方法中添加了一行以显示我的意思,使用 instanceof 确认它仍然是 ClassChild 的实例。
  • 非常感谢您的帮助。非常感谢的人
猜你喜欢
  • 1970-01-01
  • 2010-11-15
  • 2022-01-21
  • 1970-01-01
  • 2013-06-14
  • 2021-12-20
  • 2015-12-04
  • 2014-04-22
  • 1970-01-01
相关资源
最近更新 更多