This question already has answers here:
Why can't this() and super() both be used together in a constructor?
(11 answers)
Closed 5 years ago.
I have this program:
public class A
{
public A(){
System.out.println("I am in A");
}
public static void main(String args[]){
B a = new B("Test");
}
}
class B extends A
{
public B(){
System.out.println("I am in B");
}
public B(String s){
this();
super();
System.out.println("I am in B as " + s);
}
}
Now why can't I call the this constructor of B to invoke the default constructor? This is giving me compile time error.
this and super must be the first line in a constructor.
EDITED:
Language spec
8.8.7. Constructor Body
The first statement of a constructor body may be an explicit
invocation of another constructor of the same class or of the direct
superclass (§8.8.7.1).
this() calls another constructor in the same class.
super() calls a super constructor.If no super() is explicitly written,the compiler will add one implicitly. Hence, you will end up calling super() twice.
So, both are not allowed.
EDIT
In context of your code : remember, super() should always be the first line in a constructor.
Upon further reflection my answer as it was below is basically correct but lacking some nuance. Essentially, you can call a super constructor once. This is to ensure your super class is only constructed once. This means that the first line of a given constructor can be a call to another constructor in the current class or a call to a constructor in the super class. This also means that you can only call another constructor once in any given constructor; you must choose to call one in the current or super class. This ensures that all super classes will be fully constructed before the current object is.
Old explanation:
The fundamental reason is that all super classes must be constructed before the subclass can be. To this end, Java will implicitly call super() if no such invocation exist on the first line of a constructor. The only way to override this behavior is to explicitly call a different constructor in your super class. Basically, Java must create your hierarchy before you can be created.
Putting your constructor first violates this requirement and therefore is illegal.
According to Java this() and super() should be the first statement in constructor.Now the point is we can not write both at once as a first line.If u write this() and not super,dont expect that super will be called implicitly.
It is as simple as it is.U have no option to write them together in single constructor body
Related
This question already has answers here:
Overriding member variables in Java ( Variable Hiding)
(13 answers)
Java cast to superclass and call overload method
(1 answer)
Closed 5 years ago.
Super keyword related doubt.
class Parent{
int x=40;
void show()
{
System.out.println("Parent");
}
}
class Child extends Parent
{ int x=20;
void show() //method overriding has been done
{
System.out.println(super.x); // prints parent data member
System.out.println(((Parent)this).x); /*same output as previous statement which means super is similar to (Parent)this*/
System.out.println("child");
super.show(); // invokes parent show() method
((Parent)this).show(); //Doesnt invoke parent show() method.Why?
}
public static void main(String s[])
{
Child c1=new Child(); //Child class object
c1.show();
}}
So, System.out.println(super.x) and System.out.println(((Parent)this).x) prints the same value.So if super.show() calls parent class show() method then why is ((Parent)this).show(); unable to call parent show()? Please tell appropriate explaination for this.
Constructor Chaining
in Java keyword this represent current object and when one class extends another then its super class reference variable may hold child class reference variable that's is in your code is ((Parent)this).x ,
while super keyword is used to call directly super class constructor and its variables.
at the same time when super class variables holds child class object and when we use super it refers same object .
How to call one constructor from another constructor in Java or What
is Constructor Chaining in Java is one of the tricky questions in Java
interviews. Well, you can use this keyword to call one constructor
from another constructor of the same class if you want to call a
constructor from based class or super class then you can use super
keyword. Calling one constructor from other is called Constructor
chaining in Java. Constructors can call each other automatically or
explicitly using this() and super() keywords. this() denotes a
no-argument constructor of the same class and super() denotes a no
argument or default constructor of parent class. Also having multiple
constructors in the same class is known as constructor overloading in
Java.
Read more: http://www.java67.com/2012/12/how-constructor-chaining-works-in-java.html#ixzz4bJ5C069o
Calling ((Parent) this).show(); on what is really a Child object causes Child.show() to be called. Whether you are doing it as myObject.show() or through this makes no difference for which version of the method gets called — it’s always the method determined by the object’s runtime type, in this case Child.
So you have a recursive call, leading to infinite recursion.
super.show() on the other hand calls the method in the super class, in this case Parent.
I have derived a class in java.
I noticed that the superclass constructor gets called before code in my derived class constructor is executed.
Is there a way to invert that order?
Example:
class Animal
{
public Animal()
{
//do stuff
}
}
class Cat extends Animal
{
int var;
public Cat(int v)
{
var = v;
super();
}
}
This is what I would like to do, but calling super() like that gives an error...
No, there is no way to invert that order. If you explicitly call a parent class constructor you are required to do it at the top of your constructor. Calling it later would allow a child class to access the parent class's data before it's been constructed.
No, you can't invert the order of constructor calls this way. A call to super() must be the first statement in a constructor. And if there is no such call, Java inserts an implicit call to super() as the first statement.
The JLS, Section 8.8.7, states:
The first statement of a constructor body may be an explicit invocation of another constructor of the same class or of the direct superclass (§8.8.7.1).
ConstructorBody:
{ [ExplicitConstructorInvocation] [BlockStatements] }
There isn't a way to call run the sub class constructor before superclass constructor. That's basically like trying to create the subclass even before the superclass gets created, which is impossible since the subclass relies on superclass attributes to get created.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is question (and answer) from OCJP test exam. And I was very confused about it.
Here is a question review (on Kaplan SelfTest site):
Reviewing Answered
Item 64 of 90Ref: 1Z0-803.6.5.6
Which statement is true about constructor overloading?
A default constructor can be overloaded in the same class.
A default constructor can be overloaded in a subclass.
The constructor must use a different name.
The constructor must use the this keyword.
Explanation:
A default constructor can be overloaded in a subclass. If no constructor is defined for a class, then the compiler will automatically provide the default constructor. Because a subclass can define its own constructors without affecting the superclass, a constructor with parameters can be defined that invokes the superclass constructor, implicitly or explicitly.
A default constructor cannot be overloaded in the same class. This is because once a constructor is defined in a class, the compiler will not create the default constructor. Thus, an attempt to overload the default constructor will effectively remove it from the class.
The constructor must not use a different name. In the same class, an overloaded constructor uses the same name. Because subclasses differ in name from their superclass, an overloaded constructor will have a different name.
The constructor does not need to use the this keyword. The this keyword allows a constructor to reference other constructor methods and/or instance context. Using the this keyword is not required in an overloaded constructor.
Objective:
Working with Methods and Encapsulation
Sub-Objective:
Create and overload constructors
You are getting your terminology wrong.
Overloading only takes place for methods with the same name but different parameters within a specific class.
Overriding takes place for subclasses which have methods with the same "signature" (same name and parameters) as a method in the Superclass.
Note that constuctors aren't "Overridden" (by definition they have different signatures than methods in the superclass).
Instead, the compiler makes a constructor implicitly call the default constructor of its superclass (if one exists) unless you explicitly call a specific constructor of a superclass using the super keyword.
Similarly you cannot "Overload" the constructor of a superclass in a subclass (overloading doesn't work across inheritance), but you can "overload" another constructor within your specific class.
Here is an example of implicit and explicit calls to superclass constructors and overloading constructors:
public class X {
// no default constructor defined so
// compiler adds implicit default constructor here: public X(){}
}
public class Y extends X {
// explicitly declared default-constructor for class Y
public Y() {
// compiler automatically calls implicit X default constructor here
System.out.println("constructing a Y instance");
}
// explicitly declared constructor which overloads the default constructor for Y
public Y(String s) {
// compiler automatically calls implicit X default constructor here
System.out.println("constructing a Y instance with param " + s);
}
}
public class Z extends Y {
// explicitly declared default constructor for Z
public Z() {
super("Z"); // explicitly call the non-default constructor in Y here
System.out.println("constructing a Z instance");
}
}
thus constructing a Z ends up calling X(), then Y("Z") and results in this output:
Z z = new Z();
// outputs: constructing a Y instance with param Z
// constructing a Z instance
And from the docs: (http://docs.oracle.com/javase/tutorial/java/IandI/super.html)
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Hope that helps clarify things for you. If in doubt read the docs, write some code, and use System.out.println() to see what's happening.
Constructors are not technically member functions, so they aren't really inherited, and thus cannot be "overloaded". However, they can still be called from the subclass using the super keyword.
//the class being inherited
public class superclass
{
//the constructor
public superclass(some_parameter)
{
//do stuff
}
}
public class subclass extends superclass
{
public subclass(some_parameter)
{
//the super keyword here is used to access the inherited class
super(some_parameter); //this calls the constructor of the inherited class;
}
}
First, overload is not the same as override. Example:
class Foo {
void overloadedMethod() {}
void overloadedMethod(int i) {}
void overridenMethod() {}
}
class Bar extends Foo {
#Override
void overridenMethod() {}
}
Constructor can be overloaded, just as ordinary methods, but cannot be overriden.
For more info see here: link
This question already has answers here:
Difference between "this" and"super" keywords in Java
(9 answers)
Closed 9 years ago.
Can any one please tell me what is the difference between super() call and this() call in java constructors?
super() means the super class (parent) and this() means the current class.
this() calls another constructor for the same class. In this case the 0 argument one.
super() calls the constructor for the super class.
super() calls no-argument constructor from superclass and this() calls no-arg constructor from the current class.
super() calls the parent constructor of the class and this() calls the constructor defined within the class.
//Example of super()
class parent
{
parent()
{
}
}
class child()
{
child()
{
super(); //Go to parent class constructor
}
}
//Example of this
class test
{
test()
{
this("a"); //go to test one argument constructor within the test class
}
test(String a)
{
}
}
super() refers to the base/parent class. Can be used in constructor to invoke parent constructor but must be done in the declaration of the constructor.
It means you are delegating part of the object construction to another constructor, being super() a constructor defined in a superclass and this() a constructor defined in the same class.
The super() is for calling superclass' constructor . this() refers to the current class .
Here are good SO-links.
this and super in java
Difference between "this" and"super" keywords in Java
I have three classes:
public class A {
public A(){
System.out.println("in A");
}
}
public class B extends A{
public B(){
System.out.println("in b");
}
}
public class C extends B{
public C(){
System.out.println("in C");
}
}
Now I am really not sure how the constructor calls work.
If I instantiate C c= new C();, in what order (and why that order) does the constructors get called.
If I instantiate the class C, then should not it just check if the class C has got any constructor or not and if it does, it shall use it?
Why does it output-> In A In B In C?
Doesn't it go up in the hierarchy only when it doesn't find the constructor in it's own class? Or the constructors of the super class are called implicitly every time?
Super constructor are called by default from the base class constructor.
The only case in which you should call a super class constructor with super, is when you need to explicitly pass a parameter to the super class constructor itself.
So the answer is yes, they are all called. The order is from the most up class in the hierarchy down to the base class, so : A, B, C.
Default constructors are always invoked, and are invoked top-down - from the topmost super-class to the lowest base-class.
Note that the super(...) call is necessary only for parameterized constructors. In your case you don't have any, so the default gets called automatically.
When a constructor is invoked, it first calls super(), so though the stack trace will show: C->B->A, actually A will be invoked first and C will be invoked last, thus the printing will show:
in A
in B
in C
super() is implicit, as the default constructors if no constructors declared.
The constructors run upwards:
C calls B, B calls A, A calls to Object that does nothing and return to A, then outputs and return the flow to B, that outputs and return to C that outputs.
Super constructor is called by default. It is executed prior to any lines of code in the derived class's constructor. So if you call new C(), A's constructor is run, then B's, then anything in C's.
Yes when you not define any constructor it will implicitly create the default construct and call it. Now when you extends any class then like class C it go with its constructor but there it didn't find to call the super class explicitly so the compiler implicitly call the super class constructor. that why when we call the super class constructor that statement always first like this way
public C(){
super();
}
if you write any statement before calling the super class constructor you getting error
Take a look at the Java language specification
"If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments."
http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#41652
Class A is the super class for B and class B is super class of C. That means A is at the top position among them, where B is in top for C, next to A and C is sitting bottom of B. So class A execute first and then B and then C. It's like some priority in Java for super classes.