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
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.
This question already has answers here:
Java error: Implicit super constructor is undefined for default constructor
(12 answers)
Closed 4 years ago.
I have a BaseClass in a external jar, it has a constructor setting Implementation class(JerseyClientImpl) to jerseyClient.
public BaseClass(AuthDetails auth, String ID) {
setListID(D);
this.jerseyClient = new JerseyClientImpl(auth);
}
I am extending the BaseClass to set my own Implementation class to jerseyClient , but i am getting the error mentioned. Changing the BaseClass to add default constructor is not in my control as i said its an external jar.Can you suggest how can i overcome this error.
Since BaseClass has a non default constructor, it doesn't have the automatically generated parameterless default contstructor.
Therefore your sub-class can't rely on the default constructor (since it won't be able to call the non-existing default constructor of the base class), so your sub-class must have an explicit constructor that calls the constructor of the base class.
Either a constructor with the same parameters :
public SubClass(AuthDetails auth, String ID) {
super(auth,ID);
...
}
Or a constructor without parameters that gives default values for the base-class's constructor :
public SubClass() {
super(null,"something");
...
}
In Java, if you don't explicitly provide a call to a superclass constructor as the first statement in a constructor, then it will insert an implicit call to the default superclass constructor. If there is no default superclass constructor, then you get the error you have mentioned.
The JLS, Section 8.8.7, states:
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 implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.
You must explicitly call the superclass constructor, passing all arguments, with something like this:
public JerseyClientImpl(AuthDetails auth, String ID) {
super(auth, ID);
// Rest of constructor code
}
First of all, if you are writing some parameterized constructor in a class...the default no arg constructor of the class does not exist anymore.
And, when you try to create constructor of its child class, the no-arg constructor of parent class is always called first.If it doesn't exist, you get compiler error.
So, define the no arg constructor in your parent class, OR just call the parameterized constructor of parent class with some value inside the child class constructor.
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:
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