FAQ: Inheritance and Polymorphism - Using a Child Class as its Parent Class

This community-built FAQ covers the “Using a Child Class as its Parent Class” exercise from the lesson “Inheritance and Polymorphism”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Java

FAQs on the exercise Using a Child Class as its Parent Class

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hi Codecademy

Here are my questions:

  • Is is true that using a Child Class as its Parent Class (ParentClass childInstance = new ChildClass()) is just another way to create instance of a child class (ChildClass childInstance = new ChildClass())?
  • What are the real benefits of using this unusual way of creating a child instance compared to the normal way? As you mentioned in the lesson “using the explicit child as parent syntax is most helpful when we want to declare objects in bulk”, I still don’t get what you really mean

The course is superb and meticulously prepared by the way
Thanks

16 Likes

I had the same questions. I hadn’t seen this before.

After googling a bit I found this is referred to as “up casting”. The examples I saw involved saving instances of ChildClass in an array of ParentClass. When the objects are retrieved from the array they are treated as instances of ParentClass unless they are “down cast” to the ChildClass.

If the down cast is invalid (the object is not an instance of ChildClass) you get a ClassCastException. The getClass() method can be used to determine the actual class of the object so your code could avoid the exception.

3 Likes

In no way am I trying to lecture anyone on solutions. I post these with my interpretations for personal reasons, mostly making sure that I’m understanding what I’m doing. My professor has mentioned many times that trying to explain a concept is the best way to see where the gaps in your own knowledge are.

Dinner class with notes

class Dinner {
  
  private void makeNoodles(Noodle noodle, String sauce) {
    
    noodle.cook();
    
    System.out.println("Mixing " + noodle.texture + " noodles made from " + noodle.ingredients + " with " + sauce + ".");
    System.out.println("Dinner is served!");
    
  }
  
  public static void main(String[] args) {
    
    Dinner noodlesDinner = new Dinner();
    // Add your code here:
    Noodle biangBiang = new BiangBiang();
    // BiangBiang is after the keyword "new" because that is the object we are        instantiating
    // Noodle is the parentclass relative to the BiangBiang class. One level higher.
    // The compiler will think the variable/reference "biangBiang" is just a "Noodle" object. However, at runtime it will create the "BiangBiang" object we set out to create. 
    
    // The overall superclass is the Dinner class where our main() method is stored. That is what our program is ultimately created for. The Noodle and the type of noodle is just one type of dinner possibility. 
    noodlesDinner.makeNoodles(biangBiang, "soy sauce and chili oil"); 
    
    
  }
  
}

Noodle class; nothing changed here. Still contains the fields, the constructor, and the one method it had from the outset.

class Noodle {
  
  protected double lengthInCentimeters;
  protected double widthInCentimeters;
  protected String shape;
  protected String ingredients;
  protected String texture = "brittle";
  
  Noodle(double lenInCent, double wthInCent, String shp, String ingr) {
    
    this.lengthInCentimeters = lenInCent;
    this.widthInCentimeters = wthInCent;
    this.shape = shp;
    this.ingredients = ingr;
    
  }
  
  public void cook() {
    
    this.texture = "cooked";
    
  }
  
}

Nothing has changed in the child class BiangBiang either; same code that was given

class BiangBiang extends Noodle {
  
  BiangBiang() {
    
    super(50.0, 5.0, "flat", "high-gluten flour, salt, water");
    
  }
  
}
5 Likes

Could someone clarify this for me:

When we instantiate a ChildClass object as a ParentClass object, as follows:

Noodle biangBiang = new BiangBiang();

And then, we pass the arguments for the object biangBiang in the class BiangBiang. The code works fine.

However, if you try to directly pass the arguments when instantiating the object, as follows:

Noodle biangBiang = new BiangBiang(50.0, 5.0, “flat”, “high-gluten flour, salt, water”);

You get an error. Why is that?

You only pass in arguments for the constructor method when instantiating the object, but if you look at the BiangBiang.java tab, there are no parameters for the constructor method.

Can someone explain what does it mean to use a child class as its parent class and what purpose does this serve?
I don’t really understand this concept.

1 Like

Object Casting is an Important concept in java which covers upcasting and downcasting in java.In this video, we are going to cover upcasting in depth.We are going to understand the meaning of Parent p = new Child() Statement step by step.We are going to learn how to upcast manually and why explicit upcasting in not necessary in Java.So let’s understand upcasting in java which where we will also cover the dynamic method dispatch concept.

runtime polymorphism in java:

Assume we have a Parent class named ‘Parent’ and a child class named ‘Child’.
Parent p = new Child();
here ‘p’ is parent type reference and 'new child()’ is the runtime object.

So method overriding in java which is also called as runtime polymorphism is generally dealing with runtime object.So in java as we can store child class object in the parent class reference(which is called upcasting).When we call a method with parent type reference(‘p’ in our case), during runtime jvm checks for the runtime object and based on that a specific method get called.It depends on whether the method you are calling has been overridden in the child class. If the method you are calling overridden in the child class, then the child-specific method will get called otherwise the parent-specific method gets called.

So we can say in general in runtime polymorphism in java , object linking happens in the runtime.

rules :
Parent p = new Child(); //upcasting

  1. During compilation, the compiler only checks for the method that we are calling is available in the parent class or not.If yes, then compilation successful otherwise we will get compile time error saying the method is not available in the parent reference.So the calling method should be available in the parent class if we are calling the method using the parent reference.

  2. If the calling method is overridden in the child calss( inheritance in java ) then the child-specific method will be get called which is called as dynamic method dispatch.

In this video, we will also talk about dynamic dispatch in details with a tons of example.

Object casting in java :
When we talk about upcasting in java, we have to understand that the upcasting is safe and it is implicit.There is no need to do upcasting in java explicitly as jvm does it internally.

for an example :
casting sub type to a supper type is called upcasting :

Child c = new Child();

now is c is a subtype.let’s cast it to supper type

Parent p = (Parent)c;

now we have casted it to supper type which is parent type.Here we have done upcasting manually which is not necessary.so we can directly do

parent p = c ;

because upcasting is implicit, or we can directly do

Parent p = new Child();

remember that p is storing the child class object.

with ‘p’ reference we can only call parent-specific methods but to call child specific method, we have to downcast.
so we are going to talk about downcasting in java in the next video.

Note: - upcasting and downcasting are two important things in java which is used so much in real time.

Important: To perform upcasting and downcasting the two classes must have the relationship or they must extend to each other (inheritance in java);

7 Likes

Thanks so much for this, your notes really helped me understand this confusing topic!!

Dinner is not a parent class of Noodles. How can Dinner class get access to the noodles class.
(Noodles objects in Dinnner methods)

" This would be true even if kaylasAccount were instantiated as a CheckingAccount , but using the explicit child as parent syntax is most helpful when we want to declare objects in bulk"

Can someone explain this statement?

can someone tell me what is point of this swap in parent and child classes?

Note: combine all your questions into one post in future replies.


These classes are in the same package, meaning they can access one another. We only need to use import statements to import classes from other packages. See the Oracle tutorial on packages here.


Please provide the link to this lesson.


Which lesson does this come from and which parent and child classes are you referring to?


Please read the following topic so that others can more easily help you.

last two questions are regarding this lesson,

https://www.codecademy.com/courses/learn-java/lessons/java-inheritance-and-polymorphism/exercises/using-child-class-as-parent-class

The wording does seem to be a bit confusing. This statement refers back to the previous one: “We can use kaylasAccount as if it were an instance of BankAccount , in any situation where a BankAccount object would be expected.”

I believe it is trying to say that kaylasAccount can be used as if it were an instance of BankAccount (meaning it would have the same instance variables and be able to access instance/static methods of the class) even if the object was declared as

CheckingAccount kaylasAccount = new CheckingAccount();

rather than

BankAccount kaylasAccount = new CheckingAccount();

The second half of the statement, referring to “bulk”, I’m not sure about. Maybe someone else can jump in?


This is not a swap. Rather, the object of the child class is created as a member of the parent class. By doing this, we can cause the compiler to treat kaylasAccount as if it was an object of the BankAccount class. However, if we’ve overridden a method in the CheckingAccount class, that overridden method will be executed if it is called, rather than the method in the parent class. This relates to the concept of polymorphism. Polymorphism is useful because it allows us to complete a certain action in several ways. In other words, it allows for multiple implementations of one thing.

2 Likes

class Dinner {

private void makeNoodles(Noodle noodle, String sauce) {

noodle.cook();



System.out.println("Mixing " + noodle.texture + " noodles made from " + noodle.ingredients + " with " + sauce + ".");

System.out.println("Dinner is served!");

}

public static void main(String args) {

Dinner noodlesDinner = new Dinner();

// Add your code here:

}

}

// why there is no constructor for dinner class??

1 Like

There’s a typo in the Learn section. Several times, CheckingAccount is written as CheckingAcount, notably in the the second paragraph and in the code block directly following the second paragraph.

1 Like

amazing explanation been struggling with this for over a year

In this context, we’ve simply moved a lot of the functions from main to a higher-order container. Functions we previously wrote to run the program in a default parent main method (typically inside Noodle in the previous lessons) are just now in this new Dinner class. In this context, you can think of Dinner as a dummy container (stateless).

It doesn’t need a constructer right now, but it can. And you can declare instance variables of Noodle type (ie private Noodle noodle;), add your constructor that initializes noodle to a given Noodle (or a subclass of it) and refactor makeNoodles signature to achieve the same current result. The key difference would be your ability to access the instantiated noodle from this Dinner via this.noodle

I think @core3103555706’s and @design7477539042’s replies are a good start.

I can imagine how declaring an instance variable of an array type of noodles Noodle[] noodles; (or bank accounts BankAccount[] bankAccounts; that would accept an array of either BankAccount or CheckingAccount type or both) would be the perfect use-case for streamlining bulk actions via up-casting of any/all sub-classes…