Topics Index

Constructors using this keyword

If you need explanation Read this topic

If you need Answer Take test on this topic

Constructors using this keyword
What will be the output of the following program?
class CarTester
    public static void main(String s[])
        Car car = new Car("Maruti", "Wagon R", 1000, 12.4);

        System.out.println( + "'s " + car.model + " has engine power of " + + "cc.");

class Car
    Car(String company, String model, int cc, double mileage)
        company = company;
        model = model;
        cc = cc;
        mileage = mileage;

    String company;
    String model;
    int cc;
    double mileage;

A. Maruti's Wagon R has engine power of 1000cc.
B. null's null has engine power of 0cc.
C. Compilation Error - since the parameter name passed
 to the constructor can not be the same as member variable.
D. Compilation Error - since there is no default constructor.
Topic: this Keyword In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Ans is we have the this keyword concept...this refers current we create the instance for the Car class by passing the Parameters to the the constructor we are assigning these values to the we write system will assign the company value to local variable only...Bcz local variables has more order to assign to the variables in the Current object we should wirte variables with the keyword this... means company variable in the current calling the passed wont assigned to the object so that all values has default values in the Car obejct..Strings as null n char as empty and int 0...

Posted by Uday Kumar    2014-12-19 11:18:45

B is the answer

Posted by Asad Ahmed    2014-12-19 12:58:07


Concept of "SCOPE OF VARIABLE" and "THIS" KEYWORD helps understand this.

---object of car is created by passing arguement to parametrized constructor of car class.

--In parametrized constructor while assigns the value of parameters "this" keyword should be used so that the values can be assigned to "INSTANCE VARIABLE" ...but here (company=company and so on....) will assign the values to "LOCAL VARIABLES."

--so default values are printed i.e. NULL for string and 0 for INT

Posted by Mânïshå Mùlchåndânï    2014-12-21 18:21:15

This dose is now closed and the winners are Uday Kumar,  for 'First Correct Comment', Uday Kumar, Mânïshå Mùlchåndânï,  for 'Best Comment' and Uday Kumar for the 'Popular Comment'. The 'lucky liker' is Mânïshå Mùlchåndânï. Please login into Merit Campus using facebook, to claim your recharge. Go to to raise the recharge.

Posted by Merit Campus    2014-12-22 06:55:58

© meritcampus 2019

All Rights Reserved.

Open In App