Reputation: 1709
I know that when creating an object of a class the constructor builds that object. Say I had these two class:
class Vehicle {
public int a = func();
public int func() {
System.out.println("9");
return 9;
}
}
class Car extends Vehicle {
public static void main(String[] args) {
Car c = new Car();
}
}
The output of this project is "9". But why does that happen? What exactly happens when the Car constructor is called? I know that there is some type of default constructor but I am not sure how it exactly works.
Can anyone explain me the object construction with the above example?
Upvotes: 0
Views: 2794
Reputation:
I think you are misunderstanding the meaning of Car c = new Car();
.
That statement creates an object reference, and that object's reference is c
. The statement new Car();
creates an object and the reference of that object is sent stored in c
.
Upvotes: 1
Reputation: 1026
When an object is created it initiates all instance variables present in that object.(to its variable's default value if no assignment is given).
If a default constructor of a particular class(Car) is called, a call to the default constructor of its super class(Vehicle) is made first. And while creating Vehicle object its instant variable "a" is assigned to function func() and it ll be executed, Hence printing 9.
Upvotes: 0
Reputation: 65889
Car
must be constructed.Vehicle
and therefore triggers a Vehicle
construction.Vehicle
requires the initialisation of the int a
instance variable.int a
variable must be initialised to be the result of the call to func
so func
is called.func
has been called so the code prints "9".Upvotes: 1
Reputation: 1504052
The compiler provides a default constructor for Car
which is effectively:
Car() {
super();
}
And likewise Vehicle
as a default constructor of:
Vehicle() {
super();
}
Fields are initialized as part of initialization, after the call to the superclass constructor. So it's as if the Vehicle
class was actually written like this:
class Vehicle {
public int a;
Vehicle() {
super();
a = func();
}
public int func() {
System.out.println("9");
return 9;
}
}
Now does that makes sense?
See section 15.9.4 of the Java language specification for a much more detailed description.
Upvotes: 9
Reputation: 46438
When the Car constructor
is called a default call to it's super constroctor is made by the compiler which then intializes all the Super class's instance fields
. during the initialization of your a field
as it invokes func()
method which has a sysout thus it prints 9.
public Car() {
super();// this invokes parent class's default cons
}
public Vehical() {
super();// invokes Object constructor then initializes all the instance variables of class vehical
}
Upvotes: 2