| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
What is the difference between this and super keyword?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
What is the difference between this and super keyword?Using this KeywordWithin member methods or constructors of an instance Java object, this is a reference to the currently executing object on which the method or constructor was invoked. It can not appear within static methods. You can refer to any member of the current object from within an instance method or a constructor by using this:
Using super KeywordThe super keyword in a Java instance refers to the superclass of the current object.
The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs. A static initializer and static method are always invoked without an instance object. You can not using the keyword this or the keyword super in the body of a static context, otherwise results in a compile time error Note: 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. java.lang.Object does have such a constructor, so if Object is the only superclass, there is no problem.
class Superclass {
public Superclass(int m) {
....
}
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
public class Subclass extends Superclass {
public Subclass(int x, int y) {
//COMPILER ERROR!!! Because the super class does not have no-argument constructor
this.x = x;
this.y = y;
}
public void printMethod() { //overrides printMethod in Superclass
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass(9, 8);
s.printMethod();
}
}
Do not confuse by default constructor which is automatically generated by the Java compiler for a class that no other constructors have been defined in the class. A constructor without any parameters is known as a default constructor. The default constructor calls the no parameter constructor in the superclass (e.g., super()) and initialize all instance variables to default value depending on their data type. This action taken by a default constructor ensures that the inherited state of the object is initialized properly.
If you define any constructor for your class, no default constructor is automatically created. There is no a default constructor generated by compiler because there is a contructor ( |