Java quiz 41: Superclass constructor

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes   Green = Easy,  Blue = Normal,  Red = Hard
Select    31   32   33   34   35   36   37   38   39   40   41   By title 
>

The following example shows how superclass construcotr works when you call it throug a subclass constructor. Further more it shows the usage of the keyword “this” inside constructors.

Java quiz 41: Superclass constructor

Level: Normal

What is the output of the following code?

 

public class Vehicle
{
  protected String color = "black";
  
  Vehicle(String color)
  {
    this.color = "green";
  }
}

public class Car extends Vehicle
{
  int maxPassengers;
  
  Car(int maxPassengers, String color)
  {
    super("blue");
    this.maxPassengers = maxPassengers;
  }
  public static void main(String[] args)
  {
    Car car = new Car(6, "red");
    System.out.print(car.color);
  }
}
Author: Sar Maroof

Select the correct answer.

a. This program writes “green” to the standard output.
b. This program writes “black” to the standard output.
c. This program writes “blue” to the standard output.
d. This program writes “red” to the standard output.
e. This program writes “null” to the standard output.

Answer explanation

  • The statement this.color = “green”; inside the body of the superclass constructor assigns the value green to the color of the car regardless which argument (color) is passed to it. The answer will always be green.

The correct answer is: a.




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 *