Bifference between this() and super() methods?
Bifference between this() and super() methods?
Difference between this() and super() methods?
this() | super() |
---|---|
It represents the current instance of a class. | It represents the current instance of a parent class. |
It is used to access methods of a current class. | It is used to access methods of a parent class. |
It also used to call the default constructor of a same class. | It is used to call the default constructor of the parent class. |
For Java Tutorial,
For more Core Java Interview Questions and Answer,
In Object-Oriented Programming, both this()
and super()
are used to call constructors, but they have different purposes and behaviors, and they are used in different contexts.
this()
:
this()
is used to call a constructor of the same class from within another constructor of the same class.super()
:
super()
is used to call a constructor of the superclass (parent class) from within a constructor of a subclass (child class).super()
can be used to control the flow of this initialization.Here's a simple example in Java to illustrate the differences:
class Animal {
String type;
Animal(String type) {
this.type = type;
}
}
class Dog extends Animal {
String breed;
Dog(String type, String breed) {
super(type); // Calls the constructor of the superclass (Animal)
this.breed = breed;
}
}
In this example, the Dog
class extends the Animal
class. The Dog
constructor calls super(type)
to invoke the constructor of the Animal
class to properly initialize the type
field inherited from the superclass. Then, it initializes its own breed
field.
In summary, this()
is used to call constructors within the same class, while super()
is used to call constructors of the superclass in a subclass. Both this()
and super()
are useful for managing constructor logic and ensuring proper initialization in inheritance hierarchies.