简体   繁体   中英

Instancing a class with different constructor

Assuming that I have an class named class1 and a class class2 that extends it. I want to understand what would the next line mean when it comes to instancing a class object

class1 classObjectName = new class2();

I know that I am using the constructor of class2 but my question is how does this line affects method usage if I will use methods from either of classes

Also

class1 classObjectName = new class1();

class1 classObjectName = new class2();

My question is how many instances have been created after these 2 lines and is it from class1 or class2?

Thank you

I put together a example which shows some of the behavior. When assigned as the Parent, the Child instance loses access to it's Child specific methods and data but retains the data. This means if you cast it back to the Child it will be usable as the Child again.

Main:

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
  }
}

Parent:

public class ClassParent
{
   
}

Child:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM