有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java用不同的构造函数实例化一个类

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

class1 classObjectName = new class2();

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

class1 classObjectName = new class1();

class1 classObjectName = new class2();

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

多谢各位


共 (1) 个答案

  1. # 1 楼答案

    我举了一个例子,展示了一些行为。当指定为父实例时,子实例将失去对其特定于子实例的方法和数据的访问权,但会保留数据。这意味着,如果您将其投射回子对象,它将再次作为子对象使用

    主要内容:

    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()
      {
        
      }
    }