I'm having trouble wrapping my head around the concept of super(). Java Tutorials gives this example:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
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();
}
}
But if I am overriding the printMethod, why do I need to invoke the Superclass method? Why can't I just write whatever in the Subclass method of printMethod() and just move on?
There is absolutely no need to call the super.
It just helps you to call the logic contained within super class method if you require that.
Many times you want the exact logic to run and then provide your additional logic.
Overriding always does not mean providing brand new logic. Sometimes you want to provide a slight variation. For e.g., if the method returns a value, then you call the super class method and get the value. Then you make some slight modification in that object using logic in the sub class method and return it back to caller.
You can override it. In that case, the parent method is ignored. super() is used if you want the parent method to be executed in the subclass.
This is used to avoid duplicated code. Let's say you have a class:
public class SuperClass() {
private int var1;
private int var2;
private int var3;
public SuperClass() {
var1 = 1;
var2 = 2;
var3 = 3;
}
}
and a subclass:
public class SubClass() {
private int var1;
private int var2;
private int var3;
private int var4;
public SubClass() {
super();
var4 = 4;
}
}
In this example, you are using super() to invoke superclass constructor (constructor are usually used to initialize members) so you can focus on the SubClass members, and you don't have to repeat all the initialization lines (for var1, var2 and var3).
Basically the super class is the upper most level of the program. When you create a new subclass you must "inherit" from the super class using the keyword 'extends'. This does 2 things; It allows you to use any methods created in the super class, in the subclass and it also allows you overwrite methods in the super class. Basically, if you have one method you want to use in a bunch of classes you use the super class to create it and then the sub-classes can just call the method using standard dot notation.
If you just run this program, Inside PrintMethod of the subclass will call to super class "printMethod" (print "Printed in Superclass") and then execute the things you have written in the sub class method(print "Printed in Subclass").
public void printMethod() {
//super.printMethod(); // comment this line
System.out.println("Printed in Subclass");
}
if you run like this, it will print only the things that you have written in the sub class method.
Idea is, If you want use Super class method information in the sub class, then you can call like Super.MethodName().
Clear Explanation :
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
Subclass s = new Subclass();
(i) when we are creating sub class object what wiill happens?
constructor of subclss will be executed
(ii) Do we have any costructor in sub class (Subclass )
if we have dat will execute..
but we are not having so default costructor will excecute
(iii) what default costructor will have?
Subclass (){
super();
}
(iv) what super() will do?
it calls super class contructor
in super class also we are not having constructor so
will execute default constructor
Superclass(){
super();
}
super class of superclass is Object class
so Object class is the super class of evry class in java
so it will creates object of object class..
object of Object class created
|
and comes to its subclass constructor...//step (iv)
Superclass(){
super(); // executed
}
object of Object class created
|
object of Superclass craeted
so super class constuctror execution also completed so
it will creates Object of SuperClass..
then control comes to its subclass conctructor // step (iii)
so Subclass (){
super(); // executed
}
after completion of subclass constructor it creates the object of subclass
*Important point : after completion of constructor execution
Object of thet class will be created*
object of Object class created
|
object of Superclass craeted
|
object of Subclass craeted
all this happened because of Subclass s = new Subclass();
so when you created object of sub class 3 objects are created..
s.printMethod();
now you are calling a method on subclass object
^
printMethod() is there in super class and sub class
when u r calling a method on sub class object what happens?
(i) it will search for that method in outer most objest: Object of Object class
so now printMethod() is not there in object of object class
(ii) Next its searches in next superclass object ie. object of Superclass
object Superclass object having printMethod() method
(iii) so method found...eventhougth method found controll serches in next sub most object is object of subclass object....
(iv) two methos found in two object but it excecutes sub most object method.
so sub most object is Subclass object...
so it executes the subclass printMethod() method.
Note: when we call a method on object it will executes the sub most objects method if ovverriden.....
now our method is....
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
first line in this method is super.printMethod();
by default super ponts to super class object : object of Superclass
object of Superclass .printMethod() is
public void printMethod() {
System.out.println("Printed in Superclass.");
}
so prints :
Printed in Superclass.
next line is : System.out.println("Printed in Subclass");
so it prints : Printed in Subclass
Note : first while creating object it called super class constructor..
now in method called super class method..
Note:
1.if class not having any constructor jvm assigns default constructor as
ClassName(){
super(); calls super class constructor
}
if class alrdy having constructor
the first line of the constructor should be the super() call.
for example: class A{
int variablea;
A(int a){
variablea=a;
}
public static void main(String[] args) {
A a=new A(2);
}
}
in this example
A(int a){
variablea=a;
} code replaces with
A(int a){
super(); by jvm by default
variablea=a;
}
You can use super in a subclass to refer to its immediate superclass. Super has two general forms.
to call the super class's constructor from the subclass
to access a member of the superclass from the subclass
I'm assuming that you are trying to understand the second one.
An example which might make you understand how super helps in referencing members of the super class:
public class Human {
String name;
int age;
public void printDetails() {
System.out.println("Name:"+name);
System.out.println("Age:"+age);
}
}
public class Student extends Human {
int rollNumber;
String grade;
public void printDetails() {
super.printDetails();
System.out.println("Roll Number:"+rollNumber);
System.out.println("Grade:"+grade);
}
public void printNameAgeAndSayGoodMorning(){
super.printDetails();
System.out.println("Good morning!");
}
public static void main(String[] args) {
Student s = new Student();
s.name="MyName";
s.age=27;
s.rollNumber=3;
s.grade="A+";
s.printDetails();
System.out.println(); //just an empty line
s.printNameAgeAndSayGoodMorning();
}
}
I avoided constructors or any getter/setter methods for simplicity.
In this example, do you think you really have to "just write whatever in the Subclass" instead of reusing the printDetails() method available in the super class?
Related
When overridden methods are called from the Constructor of the base class then also as per the run time polymorphism concept the method defined in the sub class gets invoked. I wonder as how this is taken care of in the JVM, when control is in the base class constructor the constructor of the sub class is yet to be called and hence Object is not yet completely constructed.
I understand the ill effects of calling overriden methods from base class constructor but just wish to understand as how this is made possible.
I feel object in the heap is created before constructor is invoked and as constructor is invoked the properties are initialized. Please provide your valuable inputs for the above.
Below is the code demonstrating the same.
Base.java
public class Base {
public Base() {
System.out.println("Base constructor is executing...");
someMethod();
}
public void someMethod() {
System.out.println("someMethod defined in Base class executing...");
}
}
Sub.java
public class Sub extends Base{
public Sub() {
System.out.println("Sub constructor is executing...");
}
#Override
public void someMethod() {
System.out.println("someMethod defined in Sub class executing...");
}
}
Client.java
public class Client {
public static void main(String[] args) {
Sub obj = new Sub();
}
}
Output on console is
Base constructor is executing...
someMethod defined in Sub class executing...
Sub constructor is executing...
Does object in java created before Constructor is invoked ?
Yes, otherwise you would not have an object to initialise.
At the byte code level, the object is created first, and then the constructor is called, passing in the object to initialise. The internal name for a constructor is <init> and it's return type is always void meaning it doesn't return the object, only initialise it.
Note: Unsafe.allocateInstance will create an object without calling a constructor and is useful for de-serialization.
I've run this code
public class Redimix extends Concrete{
Redimix(){
System.out.println("r ");
}
public static void main(String[] args) {
new Redimix();
}
}
class Concrete extends Sand{
Concrete() { System.out.print("c "); }
private Concrete(String s) { }
}
abstract class Sand{
Sand(){
System.out.print("s ");
}
}
and it printed out s c r but what I was expecting is that only r my question what is the logical explanation for this?
if a parent base class is an abstract class that has a constructor and then we create another class then extend it to the base class (In our Case Concrete extends Sand) and we then create another class then extend it to the concrete class name (In our case redimix) will all constructors from the hierarchy will be called?(from top to bottom)
A constructor of the superclass is always called as the first action of a constructor.
If you do not explicitly invoke a constructor of the superclass, the default constructor (the "no args" one) is implicitly invoked.
That is correct. The parent object's constructor is always called before the childs. This ensures that the object is in a valid state and that the object that has extended another class can always know what state the object is in.
Here is the code that you provided, after the compiler has inserted the implicit constructor calls in on your behave. Note that super(); is always called first.
public class Redimix extends Concrete{
Redimix(){
super();
System.out.println("r ");
}
public static void main(String[] args) {
new Redimix();
}
}
class Concrete extends Sand{
Concrete() { super(); System.out.print("c "); }
private Concrete(String s) { }
}
abstract class Sand{
Sand(){
super(); // invoking the constructor for java.lang.Object
System.out.print("s ");
}
}
In each constructor, parent constructor is also called.
In every constructor, first statement is always super() which is calling super class constructor except for Object class
You need to understand constructor chaining for this. When you make a call to any constructor all the super class constructors are invoked first. In you constructor definition, if you dont have one compiler will add a no argument call to super class constructor something like this : super();
This is because, all the class in the hierarchy must be build before you actual class, because your class is dependent on its super class.
This class to the super class constructor should always be the first statement in your constructor definition because they must be build before this concerned class. So Object class constructor is always the first to be executed.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Use of ‘super’ keyword when accessing non-overridden superclass methods
I'm new to Java and have been reading a lot about it lately to get more knowledge and experience about the language. I have a question about inherited methods and extending classes when the compiler inserts automatic code.
I've been reading that if I create class A with some methods including lets say a method called checkDuePeriod(), and then create a class B which extends class A and its methods.
If I then call the method checkDuePeriod() within class B without using the super.checkDuePeriod() syntax, during compilation will the compiler include the super. before checkDuePeriod() or will the fact that the compiler includes the super() constructor automatically when compiling the class imply the super. call of the methods that class B calls from class A?
I'm a little confused about this. Thanks in advance.
The super class's implementation of regular methods is not automatically invoked in sub classes, but a form of the super class's constructor must be called in a sub class's constructor.
In some cases, the call to super() is implied, such as when the super class has a default (no-parameter) constructor. However, if no default constructor exists in the super class, the sub class's constructors must invoke a super class constructor directly or indirectly.
Default constructor example:
public class A {
public A() {
// default constructor for A
}
}
public class B extends A {
public B() {
super(); // this call is unnecessary; the compiler will add it implicitly
}
}
Super class without default constructor:
public class A {
public A(int i) {
// only constructor present has a single int parameter
}
}
public class B extends A {
public B() {
// will not compile without direct call to super(int)!
super(100);
}
}
If you call checkDuePeriod() in B without super., means you want to invoke the method that belongs to the this instance (represented by this within B) of B. So, it equivalent to saying this.checkDuePeriod(), so it just doesn't make sense for the compiler to add super. in the front.
super. is something that you must explicitly add to tell the compiler that you want to call the A's version of the method (it is required specially in case B has overridden the implementation provided by A for the method).
Call of super() as a default constructor (constructor with no args) can be direct or non direct but it garants that fields of extendable class are properly initialized.
for example:
public class A {
StringBuilder sb;
public A() {
sb = new StringBuilder();
}
}
public class B extends A {
public B() {
//the default constructor is called automatically
}
public void someMethod(){
//sb was not initialized in B class,
//but we can use it, because java garants that it was initialized
//and has non null value
sb.toString();
}
}
But in case of methods:
Methods implement some logic. And if we need to rewrite logic of super class we use
public class B extends A {
public B() {
}
public boolean checkDuePeriod(){
//new check goes here
}
}
and if we want just implement some extra check, using the value returned from checkDuePeriod() of superclass we should do something like this
public class B extends A {
public B() {
}
public boolean checkDuePeriod(){
if(super.checkDuePeriod()){
//extra check goes here
}else{
//do something else if need
}
return checkResult;
}
}
First about the Constructors:
- When ever an object of a class is created, its constructor is initialized and at that time immediately the constructor of its super-class is called till the Object class,
- In this process all the instance variables are declared and initialized.
- Consider this scenario.
Dog is a sub-class of Canine and Canine is a sub-class of Animal
Now when Dog object is initialized, before the object actually forms, the Canine class object must be form, and before Canine object can form the Animal class object is to be formed, and before that Object class object must be form,
So the sequence of object formed is:
Object ---> Animal ---> Canine ---> Dog
So the Constructor of the Super-Class is Called before the Sub-Class.
Now with the Method:
The most specific version of the method that class is called.
Eg:
public class A{
public void go(){
}
}
class B extends A{
public static void main(String[] args){
new B().go(); // As B has not overridden the go() method of its super class,
// so the super-class implementation of the go() will be working here
}
}
Is super() used to call the parent constructor?
Please explain super().
super() calls the parent constructor with no arguments.
It can be used also with arguments. I.e. super(argument1) and it will call the constructor that accepts 1 parameter of the type of argument1 (if exists).
Also it can be used to call methods from the parent. I.e. super.aMethod()
More info and tutorial here
Some facts:
super() is used to call the immediate parent.
super() can be used with instance members, i.e., instance variables and instance methods.
super() can be used within a constructor to call the constructor of the parent class.
OK, now let’s practically implement these points of super().
Check out the difference between program 1 and 2. Here, program 2 proofs our first statement of super() in Java.
Program 1
class Base
{
int a = 100;
}
class Sup1 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup1().Show();
}
}
Output:
200
200
Now check out program 2 and try to figure out the main difference.
Program 2
class Base
{
int a = 100;
}
class Sup2 extends Base
{
int a = 200;
void Show()
{
System.out.println(super.a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup2().Show();
}
}
Output:
100
200
In program 1, the output was only of the derived class. It couldn't print the variable of neither the base class nor the parent class. But in program 2, we used super() with variable a while printing its output, and instead of printing the value of variable a of the derived class, it printed the value of variable a of the base class. So it proves that super() is used to call the immediate parent.
OK, now check out the difference between program 3 and program 4.
Program 3
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup3 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup3().Show();
}
}
Output:
200
Here the output is 200. When we called Show(), the Show() function of the derived class was called. But what should we do if we want to call the Show() function of the parent class? Check out program 4 for the solution.
Program 4
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup4 extends Base
{
int a = 200;
void Show()
{
super.Show();
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup4().Show();
}
}
Output:
100
200
Here we are getting two outputs, 100 and 200. When the Show() function of the derived class is invoked, it first calls the Show() function of the parent class, because inside the Show() function of the derived class, we called the Show() function of the parent class by putting the super keyword before the function name.
Source article: Java: Calling super()
Yes. super(...) will invoke the constructor of the super-class.
Illustration:
Stand alone example:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
Prints:
Constructing an animal: From Dog constructor
Constructing a dog.
Is super() is used to call the parent constructor?
Yes.
Pls explain about Super().
super() is a special use of the super keyword where you call a parameterless parent constructor. In general, the super keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.
Here's the official tutorial
Calling the no-arguments super constructor is just a waste of screen space and programmer time. The compiler generates exactly the same code, whether you write it or not.
class Explicit() {
Explicit() {
super();
}
}
class Implicit {
Implicit() {
}
}
Yes, super() (lowercase) calls a constructor of the parent class. You can include arguments: super(foo, bar)
There is also a super keyword, that you can use in methods to invoke a method of the superclass
A quick google for "Java super" results in this
That is correct. Super is used to call the parent constructor. So suppose you have a code block like so
class A{
int n;
public A(int x){
n = x;
}
}
class B extends A{
int m;
public B(int x, int y){
super(x);
m = y;
}
}
Then you can assign a value to the member variable n.
I have seen all the answers. But everyone forgot to mention one very important point:
super() should be called or used in the first line of the constructor.
Just super(); alone will call the default constructor, if it exists of a class's superclass. But you must explicitly write the default constructor yourself. If you don't a Java will generate one for you with no implementations, save super(); , referring to the universal Superclass Object, and you can't call it in a subclass.
public class Alien{
public Alien(){ //Default constructor is written out by user
/** Implementation not shown…**/
}
}
public class WeirdAlien extends Alien{
public WeirdAlien(){
super(); //calls the default constructor in Alien.
}
}
For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:
public class DeveloperSteps extends ScenarioSteps {
public DeveloperSteps(Pages pages) {
super(pages);
}........
I would like to share with codes whatever I understood.
The super keyword in java is a reference variable that is used to refer parent class objects. It is majorly used in the following contexts:-
1. Use of super with variables:
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
/* Driver program to test */
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:-
Maximum Speed: 120
Use of super with methods:
/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
Output:-
This is student class
This is person class
3. Use of super with constructors:
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
/* Driver program to test*/
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output:-
Person class Constructor
Student class Constructor
What can we use SUPER for?
Accessing Superclass Members
If your method overrides some of its superclass's methods, you can invoke the overridden method through the use of the keyword super like super.methodName();
Invoking Superclass Constructors
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.
Look at the code below:
class Creature {
public Creature() {
system.out.println("Creature non argument constructor.");
}
}
class Animal extends Creature {
public Animal (String name) {
System.out.println("Animal one argument constructor");
}
public Animal (Stirng name,int age) {
this(name);
system.out.println("Animal two arguments constructor");
}
}
class Wolf extends Animal {
public Wolf() {
super("tigerwang",33);
system.out.println("Wolf non argument constructor");
}
public static void main(string[] args) {
new Wolf();
}
}
When creating an object,the JVM always first execute the constructor in the class
of the top layer in the inheritance tree.And then all the way down the inheritance tree.The
reason why this is possible to happen is that the Java compiler automatically inserts a call
to the no-argument constructor of the superclass.If there's no non-argument constructor
in the superclass and the subclass doesn't explicitly say which of the constructor is to
be executed in the superclass,you'll get a compile-time error.
In the above code,if we want to create a Wolf object successfully,the constructor of the
class has to be executed.And during that process,the two-argu-constructor in the Animal
class is invoked.Simultaneously,it explicitly invokes the one-argu-constructor in the same
class and the one-argu-constructor implicitly invokes the non-argu-constructor in the Creature
class and the non-argu-constructor again implicitly invokes the empty constructor in the Object
class.
Constructors
In a constructor, you can use it without a dot to call another constructor. super calls a constructor in the superclass; this calls a constructor in this class :
public MyClass(int a) {
this(a, 5); // Here, I call another one of this class's constructors.
}
public MyClass(int a, int b) {
super(a, b); // Then, I call one of the superclass's constructors.
}
super is useful if the superclass needs to initialize itself. this is useful to allow you to write all the hard initialization code only once in one of the constructors and to call it from all the other, much easier-to-write constructors.
Methods
In any method, you can use it with a dot to call another method. super.method() calls a method in the superclass; this.method() calls a method in this class :
public String toString() {
int hp = this.hitpoints(); // Calls the hitpoints method in this class
// for this object.
String name = super.name(); // Calls the name method in the superclass
// for this object.
return "[" + name + ": " + hp + " HP]";
}
super is useful in a certain scenario: if your class has the same method as your superclass, Java will assume you want the one in your class; super allows you to ask for the superclass's method instead. this is useful only as a way to make your code more readable.
The super keyword can be used to call the superclass constructor and to refer to a member of the superclass
When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.
At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.
public class Box {
int width;
int height;
int depth;
Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
public static void main(String[] args){
HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
}
}
class HeavyBox extends Box {
int weight;
HeavyBox(int w, int h, int d, int m) {
//call the superclass constructor
super(w, h, d);
weight = m;
}
}
super is a keyword. It is used inside a sub-class method definition to call a method defined in the superclass. Private methods of the superclass cannot be called. Only public and protected methods can be called by the super keyword. It is also used by class constructors to invoke constructors of its parent class.
Check here for further explanation.
As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.
This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .
If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.
Here is an example of this:
class A {
A() {
System.out.println("Constructor A");
}
}
class B extends A{
public B() {
System.out.println("Constructor B");
}
}
class C extends B{
public C() {
System.out.println("Constructor C");
}
public static void main(String[] args) {
C c1 = new C();
}
}
The above would output:
Constructor A
Constructor B
Constructor C
The super keyword in Java is a reference variable that is used to refer to the immediate parent class object.
Usage of Java super Keyword
super can be used to refer to the immediate parent class instance variable.
super can be used to invoke the immediate parent class method.
super() can be used to invoke immediate parent class constructor.
There are a couple of other uses.
Referencing a default method of an inherited interface:
import java.util.Collection;
import java.util.stream.Stream;
public interface SkipFirstCollection<E> extends Collection<E> {
#Override
default Stream<E> stream() {
return Collection.super.stream().skip(1);
}
}
There is also a rarely used case where a qualified super is used to provide an outer instance to the superclass constructor when instantiating a static subclass:
public class OuterInstance {
public static class ClassA {
final String name;
public ClassA(String name) {
this.name = name;
}
public class ClassB {
public String getAName() {
return ClassA.this.name;
}
}
}
public static class ClassC extends ClassA.ClassB {
public ClassC(ClassA a) {
a.super();
}
}
public static void main(String[] args) {
final ClassA a = new ClassA("jeff");
final ClassC c = new ClassC(a);
System.out.println(c.getAName());
}
}
Then:
$ javac OuterInstance.java && java OuterInstance
jeff
What is the difference between the keywords this and super?
Both are used to access constructors of class right? Can any of you explain?
Lets consider this situation
class Animal {
void eat() {
System.out.println("animal : eat");
}
}
class Dog extends Animal {
void eat() {
System.out.println("dog : eat");
}
void anotherEat() {
super.eat();
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Animal();
a.eat();
Dog d = new Dog();
d.eat();
d.anotherEat();
}
}
The output is going to be
animal : eat
dog : eat
animal : eat
The third line is printing "animal:eat" because we are calling super.eat(). If we called this.eat(), it would have printed as "dog:eat".
super is used to access methods of the base class while this is used to access methods of the current class.
Extending the notion, if you write super(), it refers to constructor of the base class, and if you write this(), it refers to the constructor of the very class where you are writing this code.
this is a reference to the object typed as the current class, and super is a reference to the object typed as its parent class.
In the constructor, this() calls a constructor defined in the current class. super() calls a constructor defined in the parent class. The constructor may be defined in any parent class, but it will refer to the one overridden closest to the current class. Calls to other constructors in this way may only be done as the first line in a constructor.
Calling methods works the same way. Calling this.method() calls a method defined in the current class where super.method() will call the same method as defined in the parent class.
From your question, I take it that you are really asking about the use of this and super in constructor chaining; e.g.
public class A extends B {
public A(...) {
this(...);
...
}
}
versus
public class A extends B {
public A(...) {
super(...);
...
}
}
The difference is simple:
The this form chains to a constructor in the current class; i.e. in the A class.
The super form chains to a constructor in the immediate superclass; i.e. in the B class.
this refers to a reference of the current class.
super refers to the parent of the current class (which called the super keyword).
By doing this, it allows you to access methods/attributes of the current class (including its own private methods/attributes).
super allows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.
super() & this()
super() - to call parent class constructor.
this() - to call same class constructor.
NOTE:
We can use super() and this() only in constructor not anywhere else, any
attempt to do so will lead to compile-time error.
We have to keep either super() or this() as the first line of the
constructor but NOT both simultaneously.
super & this keyword
super - to call parent class members(variables and methods).
this - to call same class members(variables and methods).
NOTE: We can use both of them anywhere in a class except static areas(static block or method), any
attempt to do so will lead to compile-time error.
this is used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example.
super allows access to non-private methods and fields in the super-class, and to access constructors from within the class' constructors only.
When writing code you generally don't want to repeat yourself. If you have an class that can be constructed with various numbers of parameters a common solution to avoid repeating yourself is to simply call another constructor with defaults in the missing arguments. There is only one annoying restriction to this - it must be the first line of the declared constructor. Example:
MyClass()
{
this(default1, default2);
}
MyClass(arg1, arg2)
{
validate arguments, etc...
note that your validation logic is only written once now
}
As for the super() constructor, again unlike super.method() access it must be the first line of your constructor. After that it is very much like the this() constructors, DRY (Don't Repeat Yourself), if the class you extend has a constructor that does some of what you want then use it and then continue with constructing your object, example:
YourClass extends MyClass
{
YourClass(arg1, arg2, arg3)
{
super(arg1, arg2) // calls MyClass(arg1, arg2)
validate and process arg3...
}
}
Additional information:
Even though you don't see it, the default no argument constructor always calls super() first. Example:
MyClass()
{
}
is equivalent to
MyClass()
{
super();
}
I see that many have mentioned using the this and super keywords on methods and variables - all good. Just remember that constructors have unique restrictions on their usage, most notable is that they must be the very first instruction of the declared constructor and you can only use one.
this keyword use to call constructor in the same class (other overloaded constructor)
syntax: this (args list); //compatible with args list in other constructor in the same class
super keyword use to call constructor in the super class.
syntax: super (args list); //compatible with args list in the constructor of the super class.
Ex:
public class Rect {
int x1, y1, x2, y2;
public Rect(int x1, int y1, int x2, int y2) // 1st constructor
{ ....//code to build a rectangle }
}
public Rect () { // 2nd constructor
this (0,0,width,height) // call 1st constructor (because it has **4 int args**), this is another way to build a rectangle
}
public class DrawableRect extends Rect {
public DrawableRect (int a1, int b1, int a2, int b2) {
super (a1,b1,a2,b2) // call super class constructor (Rect class)
}
}