I've put this code in the compiler
package com.employer.constractor;
public class ConstractorDemo extends A{
public ConstractorDemo(){
System.out.print("Demo");
}
public static void main(String[] args){
new ConstractorDemo();
}
}
class A {
A(){
System.out.print("A");
}
}
And it gave "ADemo"
why?
I'll appreciate any detailed answer for this case
and mention how compiler will deal exactly with that
The constructor of a base class (class A in your case) is always executed before the constructor of the class you are instantiating (class ConstractorDemo in your case). That's why A is printed before Demo.
This constructor :
public ConstractorDemo(){
System.out.print("Demo");
}
is equivalent to :
public ConstractorDemo(){
super (); // prints A
System.out.print("Demo"); // prints Demo
}
The child constructor is invoked first. The first line in the child constructor will be a call to super. WHich gives you the illusion that the parent will be invoked first. But in reality the child class's constructor calls the parent class's constructor
When you invoke a child constructor, it automatically chain the calls to it's all super classes until the chain reaches to Object class.
Though you are not invoking Invoking a super class constructor doesn't mean that you are executing only Child class constructor alone. There is a interesting fact that your super class constructors(till n'th super class, which is Object class constructor) also calls in that process(shown in your code). you can observe when you invoke any Child constructor. There is a chain call to the immediate parent class constructor from the current class. And the call continues until the Object class constructor invokes since that the possible most Parent classes super class is.
Thumb rules
If you call any specific super constructor (super or super(args)),
then that specific super constructor invokes.
If you are not calling any specific constructor, then default super
constructor(super()) invokes.
base class constructor is always executed before the class Level Constructor . it automatic call super class . So First Awill print then after that Demo as per Your example. Thanks
Whenever a subclass's constructor is called , the first default statement in it is super(); which is automatically added by the compiler,
The super(); will invoke the constructor of superclass and so, first it will execute A() and then ConstractorDemo()
Refer to this : https://www.javatpoint.com/super-keyword
Even if you want to specify super(); it needs to be the first statement of your constructor else it will give you compile time error!
Your Constructor is like this :
public ConstractorDemo()
{
super(); // u didn't specified this but compiler will automatically add it
System.out.print("Demo");
}
Related
As per constructor chaining base constructor should be called when a derived class object is created and assigned to base class reference.
And there is no default constructor in base class but then there is an explicit parameterized constructor, so java compiler does not provide default constroctor.
Without the statement "this(10);" compiler complains but then as soon as its added, compiler is fine with it. WHY??
I mean why does it not try to call the base class default constructor after adding "this(10);". It should have done a super call and then executed the added statement.
class Parent{
public Parent(int a) {
System.out.println(a);
}
}
class Child extends Parent{
public Child(){
this(10);//default value
}
public Child(int a) {
super(a);
System.out.println(a);
}
}
The Java Language Specification (§12.5) defines what happens when you create a new instance; I highlighted the most important parts for your question.
If this constructor begins with an explicit constructor invocation (§8.8.7.1) of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.
This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.
So, the key points are:
Your first constructor explicitly invokes the second constructor, so step 2 above applies; the second constructor is executed, and then step 3 is skipped.
Step 3 is where the superclass constructor gets called, so that means when a constructor invokes another constructor from the same class, then it does not directly invoke a superclass constructor.
However, if you delete this(10); from the first constructor, then the first constructor does not invoke another constructor of the same class, so step 3 applies, and a superclass constructor is implicitly invoked. This causes an error because there is no superclass constructor that can be implicitly invoked (with no arguments).
The default/implicit constructor is there only if there is no other constructor.
By adding
public Parent(int a) {
System.out.println(a);
}
you remove the default constructor of Parent.
If you want to keep the default constructor, you can write it yourself like this:
public Parent(){
}
The following constructor
public Child(){
}
will be automatically replaced to
public Child(){
super();
}
This replacement will happen if there is no constructor call(this() or super()) in the first line.
This secures that a super constructor is called in any case.
The replacement will fail if there is no constructor without arguments in the super-class (if you have replaced the default constructor with a parameterized constructor).
Because if you don't add this() to Child() constructor - compiler will insert super() statement and thus expect no-arg constructor in Parent class.
class Parent{
public Parent(int a) {
System.out.println(a);
}
}
class Child extends Parent{
public Child(){
// this(10);// Commenting this(10) as if it did not exist.
super() // inserted by compiler unless you put this() or super() yourself
}
public Child(int a) {
super(a);
System.out.println(a);
}
}
I'm dealing with a class which extends JFrame.
It's not my code and it makes a call to super before it begins constructing the GUI. I'm wondering why this is done since I've always just accessed the methods of the superclass without having to call super();
There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).
An example, where the explicit call to super() gives you some extra control over the title of the frame:
class MyFrame extends JFrame
{
public MyFrame() {
super("My Window Title");
...
}
}
A call to your parent class's empty constructor super() is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.
When your superclass doesn't have a no-arg constructor, the compiler will require you to call super with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.
Whether you call super() in your constructor or not, it doesn't affect your ability to call the methods of your parent class.
As a side note, some say that it's generally best to make that call manually for reasons of clarity.
None of the above answers answer the 'why'.
Found a good explanation here:
A subclass can have its own private data members, so a subclass can
also have its own constructors.
The constructors of the subclass can initialize only the instance
variables of the subclass. Thus, when a subclass object is
instantiated the subclass object must also automatically execute one
of the constructors of the superclass.
You might also want to read everything about the super keyword here or watch everything about the super keyword here.
We can access super class elements by using super keyword
Consider we have two classes, Parent class and Child class, with different implementations of method foo. Now in child class if we want to call the method foo of parent class, we can do so by super.foo(); we can also access parent elements by super keyword.
class parent {
String str="I am parent";
//method of parent Class
public void foo() {
System.out.println("Hello World " + str);
}
}
class child extends parent {
String str="I am child";
// different foo implementation in child Class
public void foo() {
System.out.println("Hello World "+str);
}
// calling the foo method of parent class
public void parentClassFoo(){
super.foo();
}
// changing the value of str in parent class and calling the foo method of parent class
public void parentClassFooStr(){
super.str="parent string changed";
super.foo();
}
}
public class Main{
public static void main(String args[]) {
child obj = new child();
obj.foo();
obj.parentClassFoo();
obj.parentClassFooStr();
}
}
It simply calls the default constructor of the superclass.
We use super keyword to call the members of the Superclass.
As a subclass inherits all the members (fields, methods, nested classes) from its parent and since Constructors are NOT members (They don't belong to objects. They are responsible for creating objects), they are NOT inherited by subclasses.
So we have to explicitly give the call for parent constructor so that the chain of constructor remains connected if we need to create an object for the superclass. At the time of object creation, only one constructor can be called. Through super, we can call the other constructor from within the current constructor when needed.
If you are thinking why it's there for a class that is not extending any other class, then just remember every class follows object class by default. So it's a good practice to keep super in your constructor.
Note: Even if you don't have super() in your first statement, the compiler will add it for you!
We can Access SuperClass members using super keyword
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
// Here is a subclass, called Subclass, that overrides printMethod():
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:
Printed in Superclass.
Printed in Subclass
as constructor is not a part of class,
so while calling it cannot be implemented,
by using SUPER() we can call the members and memberfunctions in constructor.
Why should a class call the call the Objects default constructor of the class Objects when the class already has a parametrized constructor and a unparametrized constructor?
Example
public abstract class Foo{
private int dim1;
public Foo(int dim1) {
super();
this.dim1 = dim1;
}
public Foo() {
this.dim1 = 0;
}
}
2. Why isn't the super() method called in the unparametrized constructor in the example above?
What could happen if I forget or I don't want to call the constructor in the Object class with super() ?
Does it matter if the class which calls the super() method (Unparametrized Object's class constructor) is abstract or not ?
Why should a class call the call the Objects default constructor of the class Objects when the class already has a parametrized constructor and a unparametrized constructor?
Just because of you have it, it doesn't mean it gets called automatically. You have to call it and that is where object instantiation begins.
Why isn't the super() method called in the unparametrized constructor in the example above?
It is not a method. It is just invoking the super class default constructor. Do you know , if you didn't call it, the Java compiler automatically inserts that statement while giving you byte code. So you need not write that super() in child constructors unless you want to call specific constructor .
What could happen if I forget or I don't want to call the constructor in the Object class with super() ?
Don't worry. As said above, compiler inserts it for you.
Does it matter if the class which calls the super() method (Unparametrized Object's class constructor) is abstract or not ?
Yes, abstract or not doesn't matter. It just calls the super class constructor.
1) You probably shouldn't. It is unnecessary. It is an extra line of code which doesn't do anything.
2) Because explicitly calling super() is entirely unnecessary if your object does not extend a class other than Object (as all classes do). You could remove it from the first constructor and nothing would change. The code would compile identically.
3) Nothing. You're not required to do it.
4) This makes no difference.
If I create an object of a sub-class with no constructors, then I know that the compiler will implicitly provide a default constructor. What if I create a constructor in the sub-class and try to access the super class constructor using the super keyword, and, now, the super class has no constructor in it. Will the compiler provide a default constructor for the super class as well?
Yes, if there is no specified constructor, there is always default empty constructor
Does the compiler provides a default constructor for the super class also???
The default constructor will be there whether or not there is a subclass that needs it. The default is supplied when the parent is compiled, not later.
...What if I created sub class Constructor and trying to access the super class constructor using the super keyword,and the super class has no constructor in it.
But it does: The default one.
It goes like this.
Lets speak about Object which is the supermost class in java, If you open an editor and just make a class, then it is presumed that It is extending Object. Every class in Java extends from Object. If you do not write your own constructor then Compiler will provide one.
But if you write your own constructor let's say a constructor with one argument, compiler will not provide you with any constructor.
Now lets say taht you extend the above class, then compiler will complain you saying that the superclass does not have a default constructor rather a custom constructor so you need to make one constructor for this child class since first constructor which is called starts from the supermost class that is OBJECT and then proceeds down the line.
Hope this answers comprehensively,
Thanks.
Yes the super always occurs even if you didnt explicit declare
public class FatherTest {
}
public class SonTest extends FatherTest{
public SonTest(String sonName){
super(); // this will always occurs
}
}
If you don't write a constructor for a class, the compiler will implicitly add an empty one for you.
That means this:
public class X {
}
is identical to this:
public class X {
public X() {
// there's also an implicit super(); added here, but that's not directly relevant
}
}
If the super class doesn't have explicit constructor, then an implicit default constructor will be added to it. So your super() will invoke that.
If the super class only have some constructors with parameters. Then super() in the sub-class won't compile. You have to explicitly use one of the defined super-class constructor super(param1, param2, ...), since super() will be called if you don't call it.
What happens (if anything) when a constructor calls 'super()' without having any superclass besides Object? Like so:
public class foo implements Serializable, Comparable {
int[] startPoint;
public foo() {
super();
startPoint = {5,9};
}
}
Edit: So if this does nothing, why would anyone explicitly write that in code? Would it make any difference if I just delete that line?
It is always OK to delete the line super(); from any constructor, and there is nothing particular about the constructors of classes that extend Object. The call of the nullary superclass constructor is always implied, so whether you write it down or not, you always get the exact same semantics.
Note that this means that if you omit a call to the superclass constructor that does something big, like start database connections or the whole GUI, all this will happen whether or not you actually write super();.
super() is the first call in constructor either it is done explicitly or implicitly.
(But of course you might need to change parameters to match parent's constructor.)
Your code:
public foo()
{
startPoint = {5,9};
}
What compiler sees from the code above:
public foo()
{
super();
startPoint = {5,9};
}
So super() is invoked whether you put it explicitly in your code or not.
Since all classes derive from Object class, you are calling constructor of Object with your super() call because your class doesn't have any intermediate parents.
There is always a super class called Object, so it will invoke constructor of Object
That just calls the Object() constructor, just as if you had any other superclass with a constructor that has no parameters.
As you stated, there is a super class (Object).
The default object constructor will be called.
It calls Object's constructor, which is empty (does nothing).
super() always call to the constructor to Object class if the class doesn't extends from one class.
Class Object is the root of the class hierarchy. Every class has Object as a super class. All objects, including arrays, implement the methods of this class.
Check this link