Java quiz 23: Upcasting and downcasting objects

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes    Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   By title 
>

This example shows what happens to the overridden methods and variables by upcasting and downcasting objects in Java.

Java quiz 23: Upcasting and downcasting objects

Level: Hard

Note: The classes Item and Book are two separate files in one package.

What happens if the following code is compiled and run?

Item.java

public class Item
{
  protected double price = 5;
  
  public double getPrice()
  {
    return price;
  }
}

Book.java

public class Book extends Item
{
  double price = 15;
  
  public double getPrice()
  {
    return price += 3;
  }
  public static void main(String[] args)
  {
    Item item = new Book();
    Book book = (Book) item;
    System.out.print(item.price);
    System.out.print(", ");
    System.out.print(item.getPrice());
    System.out.print(", ");
    System.out.print(book.price);
    System.out.print(", ");
    System.out.print(book.getPrice());
  }
}
Author: Sar Maroof

Select the correct answer.


Answer explanation

  1. By upcasting objects the overridden variable depends on the type of the object reference item, but the overridden
    methods depends on the type of the object that was created.
  2. By downcasting objects both variables and methods
    depends on the type of the object reference book.

The correct answer is: b.





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *