Online Course Discussion Forum

APCSA question

 
 
Picture of Jialin Wang
APCSA question
by Jialin Wang - Saturday, March 11, 2023, 12:13 AM
 

I am having trouble figuring out an inheritance relationship.

Suppose you have the following code:

public class Test

{

  public static void main(String[] args)

  {

      Food food = new Pizza();

      System.out.print(food.s1);

      System.out.print(food.s2);//why does this throw an error? on my debugger it says the object food does have a field called s2 at the value of 1. If a superclass calls a subclass constructor and involves some field variable that the superclass doesn't have, does Java treat it as it doesn't exist?

      

  }

}

class Food

{

    int s1;

    public Food()

    {

      s1 = 0;

    }   

}

class Pizza extends Food

{

    int s2;

    public Pizza()

    {

      super();

      s2 = 1;

    }

}

 
Picture of Dr. Kevin Wang
Re: APCSA question
by Dr. Kevin Wang - Monday, March 13, 2023, 5:04 PM
 

Does it compile at all?  The "food" variable is of "Food" class.  Even though the object it references is a "Pizza" type, the compiler would not know that, so it should not know the "s2" field is available. I would expect the compiler to give an error right there. I am surprised that the code could pass compile and start to run.