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

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);

8 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…

This is because at runtime, kaylasAccount is recognized as the CheckingAccount it is. So, what if CheckingAccount has a method transferToSavings() that BankAccount does not have? Can kaylasAccount still use that method?

Well, no. The compiler believes that kaylasAccount is just a BankAccount that doesn’t have some fancy child class transferToSavings() method, so it would throw an error.

I’m very confused by this. If kaylasAccount is a CheckingAccount, which is a subclass of BankAccount, and as such is recognized as a CheckingAccount at runtime, then why would it not have all CheckingAccount methods available? Wouldn’t that defeat the purpose of it being a subclass if as a result it loses access to its own method(s)?

This question is not really related to the casting object thing but is related to instance variables instead:

In the class Noodle:

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

}

Why is the texture “brittle” not initialized in the constructor?

A more general question is: When I declare variables that are not class variables (without “static”), are they 100% considered instance variables? Will the object have a copy of this variable for their own? Because when we create a new object, eg: Noodle something = new Noodle();, we call the constructor method Noodle(), and inside that constructor we don’t write anything about the variable texture

T

Yes, a variable (that’s not static) declared for the class , but not in a method, would be an instance variable, and every instance/object would have its own copy of that variable.
So doing this:

public class Example {
  public int x = 3;
}

is similar to doing

public class Example {
  public int x;
  public Example() {
    this.x = 3;
  }
}

In the class Noodle, this means any new instances of Noodle will start with having .texture be "brittle"
even if there is nothing for that in the constructor.

Hi everybody!
I still don’t understand how could we use Noodles class and its child class in Dinner Class. I’ve met the answer below, that we import them by import statement, but I didn’t met this statement in Dinner.java file.
Excuse me, if I wasn’t attentive enough.
Thank you!